stremiok 2.3.6 → 2.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/service/index.js CHANGED
@@ -83,6 +83,7 @@
83
83
 
84
84
  var http = require('http');
85
85
  var https = require('https');
86
+ var net = require('net');
86
87
  var tls = require('tls');
87
88
  var zlib = require('zlib');
88
89
  var crypto = require('crypto');
@@ -103,6 +104,7 @@ function log(msg) { try { console.log('[StremioK service] ' + msg); } catch (e)
103
104
  // (inherited), which does something else entirely, so only a real one is used.
104
105
  var HAS_BUFFER_FROM = typeof Buffer.from === 'function' && Buffer.from !== Uint8Array.from;
105
106
  function toBuffer(s) { return HAS_BUFFER_FROM ? Buffer.from(s, 'utf8') : new Buffer(s, 'utf8'); }
107
+ function fromBase64(s) { return HAS_BUFFER_FROM ? Buffer.from(String(s), 'base64') : new Buffer(String(s), 'base64'); }
106
108
  function allocBuffer(n) { return typeof Buffer.alloc === 'function' ? Buffer.alloc(n) : new Buffer(n); }
107
109
 
108
110
  // A callback that runs at most once, and never throws out to Node.
@@ -1035,7 +1037,17 @@ function brandMany(ids, cb) {
1035
1037
  // lookups at a time for the whole service, FS_LISTS_MAX listings at once, one drive walk.
1036
1038
  var FS_LIST_MAX = 2000, FS_PARALLEL = 12, FS_LISTS_MAX = 4;
1037
1039
  var VIDEO_EXT = /\.(mkv|mp4|m4v|avi|ts|m2ts|mts|mov|webm|wmv|mpe?g|flv|3gp|ogv|vob)$/i;
1038
- var SUB_EXT = /\.(srt|vtt|ass|ssa)$/i;
1040
+ var SUB_EXT = /\.(srt|vtt|ass|ssa|smi|sub|txt)$/i;
1041
+ // A drive's walk lists videos and subtitles; a .sub or .txt only when named like a video in its
1042
+ // folder (Film.txt for Film.mkv: not every readme), as the app takes them (local.js' sidecars).
1043
+ var WEAK_SUB_EXT = /\.(sub|txt)$/i;
1044
+ function walkWants(n, siblings) {
1045
+ if (VIDEO_EXT.test(n)) { return true; }
1046
+ if (!SUB_EXT.test(n)) { return false; }
1047
+ if (!WEAK_SUB_EXT.test(n)) { return true; }
1048
+ var low = n.toLowerCase();
1049
+ return siblings.some(function (v) { return VIDEO_EXT.test(v) && low.indexOf(v.replace(/\.[^.]+$/, '').toLowerCase()) === 0; });
1050
+ }
1039
1051
  var HIDDEN_NAME = /^(\.|\$RECYCLE\.BIN$|System Volume Information$)/i;
1040
1052
  function fsDirOk(p) {
1041
1053
  if (typeof p !== 'string' || p.length > 1024 || p.indexOf('\0') !== -1) { return false; }
@@ -1227,7 +1239,7 @@ function fsWalk(root, cb) {
1227
1239
  try {
1228
1240
  if (!e2 && st && !st.isSymbolicLink()) {
1229
1241
  if (st.isDirectory()) { if (d.depth + 1 <= FS_WALK_DEPTH) { queue.push({ rel: rel, depth: d.depth + 1 }); } else { truncated = true; } }
1230
- else if ((VIDEO_EXT.test(n) || SUB_EXT.test(n)) && files.length < FS_WALK_FILES) { files.push({ p: rel, size: st.size }); }
1242
+ else if (walkWants(n, names) && files.length < FS_WALK_FILES) { files.push({ p: rel, size: st.size }); }
1231
1243
  }
1232
1244
  } catch (x) {}
1233
1245
  step();
@@ -1248,9 +1260,34 @@ function fsWalkLeave(cb) {
1248
1260
  if (!w.cbs.length && !w.cancelled) { w.cancelled = true; _walk = null; log('drive walk stopped: nobody waiting for it'); }
1249
1261
  }
1250
1262
 
1251
- // Subtitle text: the file's encoding worked out (a byte-order mark, else UTF-8 when it reads
1252
- // as UTF-8, else Windows-1252: most older .srt files), ASS / SSA turned into SRT.
1263
+ // Subtitle text: the file's encoding worked out: a byte-order mark, else UTF-8 when it reads as
1264
+ // UTF-8, else one of the old Windows ones, told apart by their letters (oldEncoding). Passed on as
1265
+ // text: the page reads its format (SRT, WebVTT, ASS, SAMI, MicroDVD…: player-subs' parseCues).
1253
1266
  var FS_SUB_MAX = 5 * 1024 * 1024;
1267
+ // Windows-1252 (Western), -1250 (Central European) and -1251 (Cyrillic): bytes 0x80-0xFF.
1268
+ var CP1252_HIGH = '€\u0081‚ƒ„…†‡ˆ‰Š‹Œ\u008DŽ\u008F\u0090‘’“”•–—˜™š›œ\u009DžŸ'; // (0xA0 on: as Latin-1)
1269
+ var CP1250_HIGH = '€\u0081‚\u0083„…†‡\u0088‰Š‹ŚŤŽŹ\u0090‘’“”•–—\u0098™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙';
1270
+ var CP1251_HIGH = 'ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—\u0098™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕї\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F';
1271
+ // Which old encoding: Cyrillic when most letters are high bytes (Russian, Ukrainian, Serbian…);
1272
+ // else Central European when its own letters show (ą ł ś ź ż ť ř ů ě, which in Western are ¹ ³ œ Ÿ
1273
+ // and the like) more than Western's (à, ¡, ¿ starting a word); Western otherwise.
1274
+ function isLetterByte(b) { return (b >= 0x41 && b <= 0x5A) || (b >= 0x61 && b <= 0x7A) || b >= 0xC0; }
1275
+ function oldEncoding(buf) {
1276
+ var high = 0, ascii = 0, ce = 0, we = 0, n = Math.min(buf.length, 262144);
1277
+ for (var i = 0; i < n; i++) {
1278
+ var b = buf[i], prev = i ? buf[i - 1] : 0x20, next = i + 1 < n ? buf[i + 1] : 0x20;
1279
+ if ((b >= 0x41 && b <= 0x5A) || (b >= 0x61 && b <= 0x7A)) { ascii++; continue; }
1280
+ if (b < 0x80) { continue; }
1281
+ if (b >= 0xC0) { high++; }
1282
+ if (b === 0x8C || b === 0x8D || b === 0x8F || b === 0x9C || b === 0x9D || b === 0x9F || b === 0xA5 || b === 0xB9 || b === 0xB3) { ce += 3; }
1283
+ else if (b === 0xBF) { if (isLetterByte(prev)) { ce += 3; } else if (isLetterByte(next)) { we += 2; } } // (ż inside a word; ¿ before one)
1284
+ else if (b === 0xA3) { if (isLetterByte(next)) { ce += 1; } } // (Ł before letters; £ before a number)
1285
+ else if (b === 0xF8 || b === 0xD8 || b === 0xEC || b === 0xF9) { ce += 1; } // (ř Ř ě ů: ø Ø ì ù in Western, rarer)
1286
+ else if (b === 0xE0 || b === 0xC0 || b === 0xA1) { we += 2; } // (à À ¡: ŕ Ŕ ˇ in Central European, rare)
1287
+ }
1288
+ if (high > 20 && high > (high + ascii) * 0.45) { return CP1251_HIGH; }
1289
+ return ce >= 2 && ce > we ? CP1250_HIGH : CP1252_HIGH;
1290
+ }
1254
1291
  function decodeText(buf) {
1255
1292
  if (buf.length >= 2 && buf[0] === 0xFF && buf[1] === 0xFE) { return buf.slice(2).toString('utf16le'); }
1256
1293
  if (buf.length >= 2 && buf[0] === 0xFE && buf[1] === 0xFF) { // (UTF-16 big-endian: bytes swapped first)
@@ -1260,41 +1297,15 @@ function decodeText(buf) {
1260
1297
  }
1261
1298
  if (buf.length >= 3 && buf[0] === 0xEF && buf[1] === 0xBB && buf[2] === 0xBF) { return buf.slice(3).toString('utf8'); }
1262
1299
  var t = buf.toString('utf8');
1263
- if (t.indexOf('\uFFFD') === -1) { return t; }
1264
- var cp = '\u20AC\u0081\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\u008D\u017D\u008F\u0090\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\u009D\u017E\u0178';
1300
+ if (t.indexOf('�') === -1) { return t; }
1301
+ var table = oldEncoding(buf), full = table.length === 128;
1265
1302
  var out = [];
1266
- for (var j = 0; j < buf.length; j++) { var b = buf[j]; out.push(b >= 0x80 && b < 0xA0 ? cp.charAt(b - 0x80) : String.fromCharCode(b)); }
1303
+ for (var j = 0; j < buf.length; j++) {
1304
+ var b = buf[j];
1305
+ out.push(b < 0x80 ? String.fromCharCode(b) : full ? table.charAt(b - 0x80) : b < 0xA0 ? table.charAt(b - 0x80) : String.fromCharCode(b));
1306
+ }
1267
1307
  return out.join('');
1268
1308
  }
1269
- function assToSrt(text) {
1270
- var lines = text.replace(/\r/g, '').split('\n'), fmt = null, inEvents = false, cues = [];
1271
- function ts(s) {
1272
- var m = /^(\d+):(\d{2}):(\d{2})[.:](\d{1,3})$/.exec(s.trim());
1273
- if (!m) { return null; }
1274
- var cs = m[4].length === 2 ? +m[4] * 10 : m[4].length === 1 ? +m[4] * 100 : +m[4];
1275
- function two(n) { return (n < 10 ? '0' : '') + n; }
1276
- return two(+m[1]) + ':' + m[2] + ':' + m[3] + ',' + ('00' + cs).slice(-3);
1277
- }
1278
- lines.forEach(function (l) {
1279
- if (/^\[events\]/i.test(l)) { inEvents = true; return; }
1280
- if (/^\[/.test(l)) { inEvents = false; return; }
1281
- if (!inEvents) { return; }
1282
- var m = /^format\s*:\s*(.*)$/i.exec(l);
1283
- if (m) { fmt = m[1].split(',').map(function (x) { return x.trim().toLowerCase(); }); return; }
1284
- m = /^dialogue\s*:\s*(.*)$/i.exec(l);
1285
- if (!m || !fmt) { return; }
1286
- var parts = m[1].split(','), n = fmt.length;
1287
- if (parts.length < n) { return; }
1288
- var f = {};
1289
- for (var i = 0; i < n - 1; i++) { f[fmt[i]] = parts[i]; }
1290
- f[fmt[n - 1]] = parts.slice(n - 1).join(',');
1291
- var a = ts(f.start || ''), b = ts(f.end || '');
1292
- var txt = ('' + (f.text || '')).replace(/\{[^}]*\}/g, '').replace(/\\N/gi, '\n').replace(/\\h/g, ' ').trim();
1293
- if (a && b && txt) { cues.push({ a: a, b: b, t: txt }); }
1294
- });
1295
- cues.sort(function (x, y) { return x.a < y.a ? -1 : x.a > y.a ? 1 : 0; });
1296
- return cues.map(function (c, i) { return (i + 1) + '\n' + c.a + ' --> ' + c.b + '\n' + c.t; }).join('\n\n') + '\n';
1297
- }
1298
1309
  function fsSub(p, cb) {
1299
1310
  cb = once(cb);
1300
1311
  if (!SUB_EXT.test(p)) { cb({ status: 400, message: 'not a subtitle file' }); return; }
@@ -1307,7 +1318,7 @@ function fsSub(p, cb) {
1307
1318
  fs.readFile(real, function (e2, buf) {
1308
1319
  if (e2) { cb({ status: 500, message: e2.code || e2.message }); return; }
1309
1320
  var text = decodeText(buf);
1310
- cb(null, /\.(ass|ssa)$/i.test(p) ? assToSrt(text) : text);
1321
+ cb(null, text);
1311
1322
  });
1312
1323
  });
1313
1324
  });
@@ -1353,6 +1364,430 @@ function fsHash(p, cb) {
1353
1364
  });
1354
1365
  }
1355
1366
 
1367
+ // ---- What's in a video file: its header read (/live/mi, /fsmi, /dav/mi) ----
1368
+ // A file's container, length and tracks, from its header only: an MKV / WebM's EBML header,
1369
+ // Info and Tracks (through its SeekHead when they come after the start), an MP4's moov box. Read
1370
+ // in pieces (MI_CHUNK at a time), MI_BYTES and MI_READS at most whatever the file's size, by
1371
+ // MI_MS; a server that won't read from a given place (no Range) only for the start. Every length
1372
+ // the file gives is bounded by what was read (a broken or hostile file can't make it allocate,
1373
+ // loop or recurse). AVI, MPEG-TS and the rest: { container: null } (unknown).
1374
+ // The answer: { container, duration (s), size, video: { codec, width, height, bitDepth, hdr
1375
+ // ('hdr10' | 'hlg' | ''), dv: { profile, compat } }, audio: [{ codec, channels, lang, name,
1376
+ // default, forced, commentary }], subs: [{ codec, lang, name, default, forced, hi, text }],
1377
+ // cues (it can be jumped through), more (tracks left out past MI_TRACKS) }.
1378
+ var MI_BYTES = 16 * 1048576, MI_READS = 10, MI_MS = 20000, MI_CHUNK = 262144, MI_ELEMENT_MAX = 8 * 1048576, MI_TRACKS = 128, MI_ACTIVE_MAX = 2;
1379
+ var _miActive = 0;
1380
+ // readAt(offset, length, cb(err, buf, total)) -> { get(offset, length, cb(err, buf)), size() }:
1381
+ // what was read kept, so a piece already in is never asked for again.
1382
+ function miReader(readAt) {
1383
+ var pieces = [], total = null, used = 0, reads = 0;
1384
+ function have(off, len) {
1385
+ for (var i = 0; i < pieces.length; i++) {
1386
+ var p = pieces[i];
1387
+ if (off >= p.off && off + len <= p.off + p.buf.length) { return p.buf.slice(off - p.off, off - p.off + len); }
1388
+ }
1389
+ return null;
1390
+ }
1391
+ function get(off, len, cb) {
1392
+ if (!(off >= 0) || !(len >= 0)) { cb(upError('bad place in the file', 422)); return; }
1393
+ if (total !== null) { if (off >= total) { cb(null, allocBuffer(0)); return; } len = Math.min(len, total - off); }
1394
+ var h = have(off, len);
1395
+ if (h) { cb(null, h); return; }
1396
+ // (the end of a piece already read, when the file ended there: what there is)
1397
+ for (var i = 0; i < pieces.length; i++) { if (pieces[i].short && off >= pieces[i].off && off <= pieces[i].off + pieces[i].buf.length) { cb(null, pieces[i].buf.slice(off - pieces[i].off)); return; } }
1398
+ var want = Math.max(len, MI_CHUNK);
1399
+ if (total !== null) { want = Math.min(want, total - off); }
1400
+ if (reads >= MI_READS || used + want > MI_BYTES) { cb(upError('the header is too big to read', 422)); return; }
1401
+ reads++; used += want;
1402
+ readAt(off, want, function (err, buf, tot) {
1403
+ if (err) { cb(err); return; }
1404
+ if (tot > 0) { total = tot; }
1405
+ pieces.push({ off: off, buf: buf, short: buf.length < want });
1406
+ cb(null, buf.slice(0, Math.min(len, buf.length)));
1407
+ });
1408
+ }
1409
+ return { get: get, size: function () { return total; } };
1410
+ }
1411
+ // EBML (MKV / WebM): an element's ID (its length marker kept, as the spec writes IDs) and size.
1412
+ function ebmlId(b, o) {
1413
+ var x = b[o];
1414
+ if (x === undefined) { return null; }
1415
+ var n = x & 0x80 ? 1 : x & 0x40 ? 2 : x & 0x20 ? 3 : x & 0x10 ? 4 : 0;
1416
+ if (!n || o + n > b.length) { return null; }
1417
+ var v = 0;
1418
+ for (var i = 0; i < n; i++) { v = v * 256 + b[o + i]; }
1419
+ return { v: v, n: n };
1420
+ }
1421
+ function ebmlSize(b, o) {
1422
+ var x = b[o];
1423
+ if (x === undefined) { return null; }
1424
+ var n = 1, mask = 0x80;
1425
+ while (n <= 8 && !(x & mask)) { n++; mask = mask >> 1; }
1426
+ if (n > 8 || o + n > b.length) { return null; }
1427
+ var v = x & (mask - 1), all = v === mask - 1;
1428
+ for (var i = 1; i < n; i++) { v = v * 256 + b[o + i]; if (b[o + i] !== 0xFF) { all = false; } }
1429
+ return { v: all ? -1 : v, n: n }; // (-1: unknown, to the end of what holds it)
1430
+ }
1431
+ // Each child element of b[o..end): fn(id, dataStart, dataSize); false stops. Sizes past the end
1432
+ // are cut to it; 4096 children at most.
1433
+ function ebmlEach(b, o, end, fn) {
1434
+ end = Math.min(end, b.length);
1435
+ for (var n = 0; o < end && n < 4096; n++) {
1436
+ var id = ebmlId(b, o), sz = id && ebmlSize(b, o + id.n);
1437
+ if (!id || !sz) { return; }
1438
+ var d = o + id.n + sz.n, s = sz.v < 0 ? end - d : sz.v;
1439
+ if (d > end) { return; }
1440
+ if (d + s > end) { s = end - d; }
1441
+ if (fn(id.v, d, s) === false) { return; }
1442
+ o = d + s;
1443
+ }
1444
+ }
1445
+ function ebmlUint(b, d, s) { var v = 0; for (var i = 0; i < Math.min(s, 8); i++) { v = v * 256 + b[d + i]; } return v; } // (8 bytes: exact to 2^53, past any file)
1446
+ function ebmlStr(b, d, s) { return b.slice(d, d + Math.min(s, 400)).toString('utf8').replace(/\0[\s\S]*$/, '').trim(); }
1447
+ function ebmlFloat(b, d, s) { try { return s === 4 ? b.readFloatBE(d) : s === 8 ? b.readDoubleBE(d) : 0; } catch (e) { return 0; } }
1448
+ var MKV_IDS = { SEGMENT: 0x18538067, SEEKHEAD: 0x114D9B74, SEEK: 0x4DBB, SEEKID: 0x53AB, SEEKPOS: 0x53AC, INFO: 0x1549A966, SCALE: 0x2AD7B1, DURATION: 0x4489,
1449
+ TRACKS: 0x1654AE6B, CLUSTER: 0x1F43B675, CUES: 0x1C53BB6B, DOCTYPE: 0x4282 };
1450
+ // A codec, short and the same whatever the container: h264, hevc, av1, vp9, aac, ac3, eac3,
1451
+ // dts, truehd, flac, opus, srt, ass, pgs… ('' unknown).
1452
+ var MI_CODECS = [
1453
+ [/^V_MPEG4\/ISO\/AVC|^(avc1|avc3)$/, 'h264'], [/^V_MPEGH\/ISO\/HEVC|^(hvc1|hev1|dvh1|dvhe)$/, 'hevc'], [/^V_AV1|^(av01|dav1)$/, 'av1'], [/^V_VP9|^vp09$/, 'vp9'],
1454
+ [/^V_VP8|^vp08$/, 'vp8'], [/^V_MPEG2|^(mp2v|m2v1)$/, 'mpeg2'], [/^V_MPEG4\/ISO\/(SP|ASP|AP)|^V_MS\/VFW|^mp4v$/, 'mpeg4'], [/^V_REAL/, 'real'], [/^(dvav|dva1)$/, 'h264'],
1455
+ [/^A_AAC|^mp4a$/, 'aac'], [/^A_AC3|^ac-3$/, 'ac3'], [/^A_EAC3|^ec-3$/, 'eac3'], [/^A_DTS|^dts[chle]$|^dtsx$/, 'dts'], [/^A_TRUEHD|^mlpa$/, 'truehd'], [/^A_FLAC|^fLaC$/, 'flac'],
1456
+ [/^A_OPUS|^Opus$/, 'opus'], [/^A_VORBIS/, 'vorbis'], [/^A_MPEG\/L3|^\.mp3$/, 'mp3'], [/^A_MPEG\/L2/, 'mp2'], [/^A_PCM|^(lpcm|ipcm|sowt|twos)$/, 'pcm'], [/^A_ALAC|^alac$/, 'alac'],
1457
+ [/^S_TEXT\/UTF8|^S_TEXT\/ASCII/, 'srt'], [/^S_TEXT\/ASS|^S_ASS/, 'ass'], [/^S_TEXT\/SSA|^S_SSA/, 'ssa'], [/^S_TEXT\/WEBVTT|^D_WEBVTT|^wvtt$/, 'vtt'], [/^S_HDMV\/PGS/, 'pgs'],
1458
+ [/^S_VOBSUB/, 'vobsub'], [/^S_DVBSUB/, 'dvb'], [/^S_HDMV\/TEXTST/, 'textst'], [/^tx3g$/, 'mov_text'], [/^stpp$/, 'ttml'], [/^c608$/, 'cc608'], [/^S_TEXT\/USF/, 'usf']];
1459
+ var MI_TEXT_SUBS = /^(srt|ass|ssa|vtt|mov_text|ttml|usf|textst)$/;
1460
+ function miCodec(id) {
1461
+ id = String(id || '');
1462
+ for (var i = 0; i < MI_CODECS.length; i++) { if (MI_CODECS[i][0].test(id)) { return MI_CODECS[i][1]; } }
1463
+ return '';
1464
+ }
1465
+ // A Dolby Vision configuration record (dvcC / dvvC): { profile, compat } (compat 1: an HDR10
1466
+ // layer underneath, 4: HLG, 2: SDR, 0: none).
1467
+ function miDv(b, d, s) {
1468
+ if (s < 5) { return null; }
1469
+ return { profile: (b[d + 2] >> 1) & 0x7F, compat: b[d + 4] >> 4 };
1470
+ }
1471
+ function miMkvTrack(b, d, s) {
1472
+ var t = { type: 0, codec: '', lang: 'eng', name: '', default: true, forced: false, hi: false, commentary: false };
1473
+ ebmlEach(b, d, d + s, function (id, cd, cs) {
1474
+ if (id === 0x83) { t.type = ebmlUint(b, cd, cs); }
1475
+ else if (id === 0x86) { t.codecId = ebmlStr(b, cd, cs); t.codec = miCodec(t.codecId); }
1476
+ else if (id === 0x63A2 && cs >= 4) { t.priv = [cd, cs]; } // (CodecPrivate: HEVC's or AV1's record, its bit depth)
1477
+ else if (id === 0x22B59C) { t.lang = ebmlStr(b, cd, cs).slice(0, 12); }
1478
+ else if (id === 0x22B59D) { t.bcp = ebmlStr(b, cd, cs).slice(0, 35); }
1479
+ else if (id === 0x536E) { t.name = ebmlStr(b, cd, cs).slice(0, 120); }
1480
+ else if (id === 0x88) { t.default = ebmlUint(b, cd, cs) !== 0; }
1481
+ else if (id === 0x55AA) { t.forced = ebmlUint(b, cd, cs) !== 0; }
1482
+ else if (id === 0x55AB) { t.hi = ebmlUint(b, cd, cs) !== 0; }
1483
+ else if (id === 0x55AF) { t.commentary = ebmlUint(b, cd, cs) !== 0; }
1484
+ else if (id === 0xE0) { // Video
1485
+ ebmlEach(b, cd, cd + cs, function (vid, vd, vs) {
1486
+ if (vid === 0xB0) { t.width = ebmlUint(b, vd, vs); }
1487
+ else if (vid === 0xBA) { t.height = ebmlUint(b, vd, vs); }
1488
+ else if (vid === 0x55B0) { // Colour
1489
+ ebmlEach(b, vd, vd + vs, function (cid, xd, xs) {
1490
+ if (cid === 0x55B2) { t.bitDepth = ebmlUint(b, xd, xs); }
1491
+ else if (cid === 0x55BA) { var tc = ebmlUint(b, xd, xs); t.hdr = tc === 16 ? 'hdr10' : tc === 18 ? 'hlg' : ''; }
1492
+ });
1493
+ }
1494
+ });
1495
+ }
1496
+ else if (id === 0xE1) { // Audio
1497
+ ebmlEach(b, cd, cd + cs, function (aid, ad, as) { if (aid === 0x9F) { t.channels = ebmlUint(b, ad, as); } });
1498
+ }
1499
+ else if (id === 0x41E4) { // BlockAdditionMapping: Dolby Vision's record
1500
+ var kind = 0, extra = null;
1501
+ ebmlEach(b, cd, cd + cs, function (mid, md, ms) { if (mid === 0x41E7) { kind = ebmlUint(b, md, ms); } else if (mid === 0x41ED) { extra = [md, ms]; } });
1502
+ if ((kind === 0x64766343 || kind === 0x64767643) && extra) { t.dv = miDv(b, extra[0], extra[1]); }
1503
+ }
1504
+ });
1505
+ if (t.bcp) { t.lang = t.bcp; }
1506
+ if (t.priv && !t.bitDepth) {
1507
+ if (t.codec === 'hevc' && t.priv[1] >= 19 && b[t.priv[0]] === 1) { t.bitDepth = (b[t.priv[0] + 17] & 7) + 8; }
1508
+ else if (t.codec === 'av1') { t.bitDepth = (b[t.priv[0] + 2] & 0x40) ? ((b[t.priv[0] + 2] & 0x20) ? 12 : 10) : 8; }
1509
+ }
1510
+ return t;
1511
+ }
1512
+ // The tracks as answered: the first video, every audio and subtitle (MI_TRACKS at most).
1513
+ function miTracks(out, list) {
1514
+ var n = 0;
1515
+ list.forEach(function (t) {
1516
+ if (n >= MI_TRACKS) { out.more = true; return; }
1517
+ if (t.type === 1 && !out.video) {
1518
+ out.video = { codec: t.codec, width: t.width || 0, height: t.height || 0, bitDepth: t.bitDepth || 0, hdr: t.hdr || '' };
1519
+ if (t.dv) { out.video.dv = t.dv; }
1520
+ n++;
1521
+ } else if (t.type === 2) {
1522
+ out.audio.push({ codec: t.codec, channels: t.channels || 0, lang: t.lang || '', name: t.name || '', default: !!t.default, forced: !!t.forced, commentary: !!t.commentary || /commentary/i.test(t.name || '') });
1523
+ n++;
1524
+ } else if (t.type === 17) {
1525
+ out.subs.push({ codec: t.codec, lang: t.lang || '', name: t.name || '', default: !!t.default, forced: !!t.forced || /forced/i.test(t.name || ''), hi: !!t.hi || /\bSDH\b|hearing/i.test(t.name || ''), text: MI_TEXT_SUBS.test(t.codec) });
1526
+ n++;
1527
+ }
1528
+ });
1529
+ }
1530
+ function miMkv(r, out, cb) {
1531
+ var I = MKV_IDS, segData = 0, segEnd = Infinity, seek = {}, got = {}, steps = 0, jumps = 0;
1532
+ r.get(0, 64, function (e, b) {
1533
+ var id = !e && ebmlId(b, 0), sz = id && ebmlSize(b, id.n);
1534
+ if (!sz || sz.v < 0) { cb(e || upError('not a Matroska file', 422)); return; }
1535
+ ebmlEach(b, id.n + sz.n, id.n + sz.n + sz.v, function (cid, d, s) { if (cid === I.DOCTYPE && ebmlStr(b, d, s) === 'webm') { out.container = 'webm'; } });
1536
+ var at = id.n + sz.n + sz.v;
1537
+ r.get(at, 16, function (e2, b2) {
1538
+ var sid = !e2 && ebmlId(b2, 0), ssz = sid && ebmlSize(b2, sid.n);
1539
+ if (!ssz || sid.v !== I.SEGMENT) { cb(e2 || upError('no Matroska segment', 422)); return; }
1540
+ segData = at + sid.n + ssz.n;
1541
+ if (ssz.v >= 0) { segEnd = segData + ssz.v; }
1542
+ walk(segData);
1543
+ });
1544
+ });
1545
+ function parse(id, b) {
1546
+ if (id === I.INFO) {
1547
+ var scale = 1000000, dur = 0;
1548
+ ebmlEach(b, 0, b.length, function (cid, d, s) { if (cid === I.SCALE) { scale = ebmlUint(b, d, s) || 1000000; } else if (cid === I.DURATION) { dur = ebmlFloat(b, d, s); } });
1549
+ if (dur > 0 && isFinite(dur)) { out.duration = Math.round(dur * scale / 1e6) / 1000; }
1550
+ got.info = true;
1551
+ } else if (id === I.TRACKS) {
1552
+ var list = [];
1553
+ ebmlEach(b, 0, b.length, function (cid, d, s) { if (cid === 0xAE) { list.push(miMkvTrack(b, d, s)); } });
1554
+ miTracks(out, list);
1555
+ got.tracks = true;
1556
+ } else if (id === I.SEEKHEAD && !got.seek) { // (the first one only: one pointing at itself can't send it round)
1557
+ got.seek = true;
1558
+ ebmlEach(b, 0, b.length, function (cid, d, s) {
1559
+ if (cid !== I.SEEK) { return; }
1560
+ var sid = 0, pos = -1;
1561
+ ebmlEach(b, d, d + s, function (x, xd, xs) { if (x === I.SEEKID) { sid = ebmlUint(b, xd, xs); } else if (x === I.SEEKPOS) { pos = ebmlUint(b, xd, xs); } });
1562
+ if (pos >= 0) { if (sid === I.INFO) { seek.info = pos; } else if (sid === I.TRACKS) { seek.tracks = pos; } else if (sid === I.CUES) { out.cues = true; } }
1563
+ });
1564
+ }
1565
+ }
1566
+ function element(at, then) { // one element at at: read and parsed when it's one wanted; then(next place, its id)
1567
+ r.get(at, 16, function (e, b) {
1568
+ var id = !e && ebmlId(b, 0), sz = id && ebmlSize(b, id.n);
1569
+ if (!sz) { then(-1, 0); return; }
1570
+ var d = at + id.n + sz.n;
1571
+ if (sz.v < 0 || id.v === I.CLUSTER) { then(-1, id.v); return; }
1572
+ if (id.v === I.CUES) { out.cues = true; }
1573
+ if ((id.v === I.INFO || id.v === I.TRACKS || id.v === I.SEEKHEAD) && sz.v <= MI_ELEMENT_MAX) {
1574
+ r.get(d, sz.v, function (e2, body) { if (!e2) { parse(id.v, body); } then(d + sz.v, id.v); });
1575
+ return;
1576
+ }
1577
+ then(d + sz.v, id.v);
1578
+ });
1579
+ }
1580
+ function walk(at) {
1581
+ if (got.info && got.tracks) { cb(null); return; }
1582
+ if (at < 0 || at >= segEnd || steps++ > 64 || (r.size() !== null && at >= r.size())) { fromSeek(); return; }
1583
+ element(at, walk);
1584
+ }
1585
+ function fromSeek() { // (Info or Tracks after the clusters: where its SeekHead says)
1586
+ var want = !got.tracks && seek.tracks >= 0 ? seek.tracks : !got.info && seek.info >= 0 ? seek.info : -1;
1587
+ if (jumps++ >= 2) { want = -1; }
1588
+ if (want < 0) { cb(got.tracks ? null : upError('no track list found', 422)); return; }
1589
+ if (want === seek.tracks) { seek.tracks = -1; } else { seek.info = -1; }
1590
+ element(segData + want, function () { fromSeek(); });
1591
+ }
1592
+ }
1593
+ // MP4 / MOV: the top-level boxes walked to moov, read when it's MI_ELEMENT_MAX or less.
1594
+ function mp4Each(b, o, end, fn) {
1595
+ end = Math.min(end, b.length);
1596
+ for (var n = 0; o + 8 <= end && n < 4096; n++) {
1597
+ var size = b.readUInt32BE(o), type = b.toString('binary', o + 4, o + 8), hdr = 8;
1598
+ if (size === 1) { if (o + 16 > end) { return; } size = b.readUInt32BE(o + 8) * TWO32 + b.readUInt32BE(o + 12); hdr = 16; }
1599
+ else if (size === 0) { size = end - o; }
1600
+ if (size < hdr) { return; }
1601
+ if (fn(type, o + hdr, Math.min(size, end - o) - hdr) === false) { return; }
1602
+ o += size;
1603
+ }
1604
+ }
1605
+ var MP4_GENERIC_NAMES = /handler|^core media|^mainconcept|^gpac|^l-smash|^apple |^isomedia|^bento4|^video$|^audio$|^sound$|^subtitle$|^text$/i;
1606
+ function miMp4Track(b, d, s) {
1607
+ var t = { type: 0, codec: '', lang: '', name: '', default: false };
1608
+ (function walk(o, end, depth) {
1609
+ if (depth > 6) { return; }
1610
+ mp4Each(b, o, end, function (type, bd, bs) {
1611
+ if (type === 'mdia' || type === 'minf' || type === 'stbl' || type === 'udta') { walk(bd, bd + bs, depth + 1); }
1612
+ else if (type === 'tkhd' && bs >= 4) { t.enabled = (b[bd + 3] & 1) === 1; }
1613
+ else if (type === 'mdhd' && bs >= 24) {
1614
+ var lo = b[bd] === 1 ? bd + 32 : bd + 20;
1615
+ if (lo + 2 <= bd + bs) { var l = b.readUInt16BE(lo); if (l && l !== 0x7FFF) { t.lang = String.fromCharCode(((l >> 10) & 31) + 0x60, ((l >> 5) & 31) + 0x60, (l & 31) + 0x60); } }
1616
+ }
1617
+ else if (type === 'hdlr' && bs >= 12) {
1618
+ var h = b.toString('binary', bd + 8, bd + 12);
1619
+ t.type = h === 'vide' ? 1 : h === 'soun' ? 2 : (h === 'subt' || h === 'text' || h === 'sbtl' || h === 'clcp') ? 17 : 0;
1620
+ var nm = bs > 24 ? b.slice(bd + 24, bd + Math.min(bs, 24 + 200)).toString('utf8').replace(/\0[\s\S]*$/, '').trim() : '';
1621
+ if (nm && !MP4_GENERIC_NAMES.test(nm) && !t.name) { t.name = nm.slice(0, 120); }
1622
+ }
1623
+ else if (type === 'name' && bs > 0 && bs < 400) { var un = b.slice(bd, bd + bs).toString('utf8').replace(/\0/g, '').trim(); if (un && !MP4_GENERIC_NAMES.test(un)) { t.name = un.slice(0, 120); } }
1624
+ else if (type === 'stsd' && bs >= 16) { mp4Each(b, bd + 8, bd + bs, function (et, ed, es) { entry(et, ed, es); return false; }); }
1625
+ });
1626
+ })(d, d + s, 0);
1627
+ function entry(type, ed, es) { // the first sample description: its codec, and what's in it
1628
+ t.codecId = type;
1629
+ t.codec = miCodec(type);
1630
+ if (/^(dvh1|dvhe|dvav|dva1)$/.test(type)) { t.dv = t.dv || { profile: 0, compat: 0 }; }
1631
+ if (t.type === 1 && es >= 78) {
1632
+ t.width = b.readUInt16BE(ed + 24); t.height = b.readUInt16BE(ed + 26);
1633
+ mp4Each(b, ed + 78, ed + es, function (ct, cd, cs) {
1634
+ if ((ct === 'dvcC' || ct === 'dvvC') && cs >= 5) { t.dv = miDv(b, cd, cs); }
1635
+ else if (ct === 'colr' && cs >= 10 && b.toString('binary', cd, cd + 4) === 'nclx') { var tc = b.readUInt16BE(cd + 6); t.hdr = tc === 16 ? 'hdr10' : tc === 18 ? 'hlg' : ''; }
1636
+ else if (ct === 'hvcC' && cs >= 19) { t.bitDepth = (b[cd + 17] & 7) + 8; }
1637
+ else if (ct === 'av1C' && cs >= 3) { t.bitDepth = (b[cd + 2] & 0x40) ? ((b[cd + 2] & 0x20) ? 12 : 10) : 8; }
1638
+ });
1639
+ } else if (t.type === 2 && es >= 28) {
1640
+ t.channels = b.readUInt16BE(ed + 16);
1641
+ mp4Each(b, ed + 28, ed + es, function (ct, cd, cs) {
1642
+ var acmod = -1, lfe = 0;
1643
+ if (ct === 'dac3' && cs >= 3) { var v = (b[cd] << 16) | (b[cd + 1] << 8) | b[cd + 2]; acmod = (v >> 11) & 7; lfe = (v >> 10) & 1; }
1644
+ else if (ct === 'dec3' && cs >= 6) { var u = b.readUInt32BE(cd + 2); acmod = (u >>> 17) & 7; lfe = (u >>> 16) & 1; }
1645
+ if (acmod >= 0) { t.channels = [2, 1, 2, 3, 3, 4, 4, 5][acmod] + lfe; }
1646
+ });
1647
+ }
1648
+ }
1649
+ return t;
1650
+ }
1651
+ function miMp4(r, out, cb) {
1652
+ var steps = 0;
1653
+ out.container = 'mp4';
1654
+ (function box(at) {
1655
+ if (steps++ > 32 || (r.size() !== null && at >= r.size())) { cb(upError('no moov box found', 422)); return; }
1656
+ r.get(at, 16, function (e, b) {
1657
+ if (e || b.length < 8) { cb(e || upError('no moov box found', 422)); return; }
1658
+ var size = b.readUInt32BE(0), type = b.toString('binary', 4, 8), hdr = 8;
1659
+ if (size === 1) { if (b.length < 16) { cb(upError('a broken box', 422)); return; } size = b.readUInt32BE(8) * TWO32 + b.readUInt32BE(12); hdr = 16; }
1660
+ else if (size === 0) { size = r.size() !== null ? r.size() - at : -1; }
1661
+ if (!/^[\x20-\x7e]{4}$/.test(type) || size < hdr) { cb(upError('not an MP4 file', 422)); return; }
1662
+ if (type === 'qt ' || type === 'ftyp') { if (type === 'ftyp' && b.length >= 12 && b.toString('binary', 8, 12) === 'qt ') { out.container = 'mov'; } }
1663
+ if (type !== 'moov') { box(at + size); return; }
1664
+ if (size - hdr > MI_ELEMENT_MAX) { cb(upError('the header is too big to read', 422)); return; }
1665
+ r.get(at + hdr, size - hdr, function (e2, m) {
1666
+ if (e2) { cb(e2); return; }
1667
+ var list = [], ts = 0, dur = 0;
1668
+ mp4Each(m, 0, m.length, function (t, d, s) {
1669
+ if (t === 'mvhd' && s >= 20) {
1670
+ if (m[d] === 1 && s >= 32) { ts = m.readUInt32BE(d + 20); dur = m.readUInt32BE(d + 24) * TWO32 + m.readUInt32BE(d + 28); }
1671
+ else { ts = m.readUInt32BE(d + 12); dur = m.readUInt32BE(d + 16); }
1672
+ }
1673
+ else if (t === 'trak') { list.push(miMp4Track(m, d, s)); }
1674
+ else if (t === 'mvex') { out.fragmented = true; }
1675
+ });
1676
+ if (ts > 0 && dur > 0 && dur < 0xFFFFFFFF) { out.duration = Math.round(dur / ts * 1000) / 1000; }
1677
+ var firstOf = {};
1678
+ list.forEach(function (t) { if (!firstOf[t.type] && t.enabled !== false) { firstOf[t.type] = true; t.default = true; } }); // (MP4 has no default flag: the first enabled one plays)
1679
+ miTracks(out, list);
1680
+ out.cues = true; // (an MP4's sample tables: always seekable)
1681
+ cb(null);
1682
+ });
1683
+ });
1684
+ })(0);
1685
+ }
1686
+ // The file's header read through readAt (see miReader): cb(err, answer).
1687
+ function mediaInfo(readAt, cb) {
1688
+ cb = once(cb);
1689
+ if (_miActive >= MI_ACTIVE_MAX) { cb(upError('busy', 503)); return; }
1690
+ _miActive++;
1691
+ var done = false, timer = setTimeout(function () { finish(upError('timed out', 504)); }, MI_MS);
1692
+ function finish(err, val) { if (done) { return; } done = true; clearTimeout(timer); _miActive--; cb(err, val); }
1693
+ var r = miReader(readAt), out = { container: null, duration: 0, size: 0, video: null, audio: [], subs: [], cues: false };
1694
+ r.get(0, 64, function (e, b) {
1695
+ if (e) { finish(e); return; }
1696
+ var then = function (err) { out.size = r.size() || 0; if (err && !out.video && !out.audio.length) { finish(err); return; } finish(null, out); };
1697
+ if (b.length >= 4 && b.readUInt32BE(0) === 0x1A45DFA3) { out.container = 'mkv'; miMkv(r, out, then); }
1698
+ else if (b.length >= 8 && /^(ftyp|moov|mdat|free|skip|wide|pnot)$/.test(b.toString('binary', 4, 8))) { miMp4(r, out, then); }
1699
+ else { out.size = r.size() || 0; finish(null, out); } // (AVI, MPEG-TS…: not read)
1700
+ });
1701
+ return function () { finish(upError('stopped', 499)); };
1702
+ }
1703
+ // readAt for a link (a source's): Range requests with its own headers, its redirects followed
1704
+ // once (the next pieces asked at the final address), not into the home network from outside it
1705
+ // unless lan, never to the TV itself; a server that ignores Range: only from the start.
1706
+ function miHttpReader(url, who, lan, stops) {
1707
+ var at = url, firstHost = null, hops = 0;
1708
+ return function readAt(off, len, cb) {
1709
+ cb = once(cb);
1710
+ var pu;
1711
+ try { pu = urllib.parse(at); } catch (e) { cb(upError('bad link', 400)); return; }
1712
+ if ((pu.protocol !== 'http:' && pu.protocol !== 'https:') || !dlHostOk(pu.hostname)) { cb(upError('a link it can\'t follow', 400)); return; }
1713
+ if (firstHost === null) { firstHost = pu.hostname; }
1714
+ else if (!fileHopOk(firstHost, pu.hostname, lan)) { cb(upError('a link into your home network', 403)); return; }
1715
+ var h = liveHeaders(who), r = null, chunks = [], got = 0, ended = false;
1716
+ h.Range = 'bytes=' + off + '-' + (off + len - 1);
1717
+ h['Accept-Encoding'] = 'identity';
1718
+ var opts = { hostname: pu.hostname, port: pu.port, path: pu.path, method: 'GET', headers: h };
1719
+ if (pu.protocol === 'https:' && caList().length) { opts.ca = caList(); }
1720
+ function end(err, total) {
1721
+ if (ended) { return; }
1722
+ ended = true; clearTimeout(timer);
1723
+ try { if (r) { r.abort(); } } catch (e) {}
1724
+ if (err) { cb(err); return; }
1725
+ var buf = Buffer.concat(chunks, got);
1726
+ cb(null, buf.length > len ? buf.slice(0, len) : buf, total);
1727
+ }
1728
+ var timer = setTimeout(function () { end(upError('timed out', 504)); }, 12000);
1729
+ stops.push(function () { end(upError('stopped', 499)); });
1730
+ try {
1731
+ r = (pu.protocol === 'https:' ? https : http).request(opts, function (resp) {
1732
+ if (ended) { resp.resume(); return; }
1733
+ var sc = resp.statusCode, total = 0;
1734
+ if (sc >= 300 && sc < 400 && resp.headers.location && hops < 5) {
1735
+ resp.resume(); hops++; ended = true; clearTimeout(timer);
1736
+ try { at = urllib.resolve(at, String(resp.headers.location)); } catch (e) { cb(upError('bad link', 400)); return; }
1737
+ readAt(off, len, cb);
1738
+ return;
1739
+ }
1740
+ if (sc === 200 && off > 0) { resp.resume(); end(upError('the server only sends the whole file', 502)); return; }
1741
+ if (sc !== 200 && sc !== 206) { resp.resume(); end(upError('HTTP ' + sc, sc >= 400 && sc < 600 ? sc : 502)); return; }
1742
+ var cr = /\/(\d+)\s*$/.exec(String(resp.headers['content-range'] || ''));
1743
+ total = cr ? +cr[1] : sc === 200 ? +(resp.headers['content-length'] || 0) : 0;
1744
+ resp.on('data', function (c) { if (ended) { return; } chunks.push(c); got += c.length; if (got >= len) { end(null, total); } });
1745
+ resp.on('end', function () { end(null, total); });
1746
+ resp.on('error', function () { end(upError('the host stopped sending', 502)); });
1747
+ });
1748
+ guardSelf(r, function () { end(upError('a link it can\'t follow', 400)); });
1749
+ r.on('error', function (e) { end(upError((e && e.message) || 'network error', 502)); });
1750
+ r.end();
1751
+ } catch (e) { end(upError('bad link', 400)); }
1752
+ };
1753
+ }
1754
+ // readAt for a file on a USB drive (a video, on a drive: fsRealOk); done() closes it.
1755
+ function miFileReader(p, cb) {
1756
+ if (!VIDEO_EXT.test(p)) { cb({ status: 400, message: 'not a video file' }); return; }
1757
+ fsRealOk(p, function (err, real) {
1758
+ if (err) { cb(err); return; }
1759
+ var fs = require('fs');
1760
+ fs.open(real, 'r', function (e, fd) {
1761
+ if (e) { cb({ status: 404, message: e.code || e.message }); return; }
1762
+ fs.fstat(fd, function (e1, st) {
1763
+ var size = !e1 && st ? st.size : 0;
1764
+ cb(null, function readAt(off, len, rcb) {
1765
+ var n = Math.max(0, Math.min(len, size - off)), buf = allocBuffer(n);
1766
+ if (!n) { rcb(null, buf, size); return; }
1767
+ fs.read(fd, buf, 0, n, off, function (e2, got) { if (e2) { rcb({ status: 500, message: e2.code || e2.message }); return; } rcb(null, buf.slice(0, got), size); });
1768
+ }, function done() { fs.close(fd, function () {}); });
1769
+ });
1770
+ });
1771
+ });
1772
+ }
1773
+ // readAt for a file in a network folder (davReq: its sign-in, its certificate).
1774
+ function miDavReader(f, url, stops) {
1775
+ return function readAt(off, len, cb) {
1776
+ stops.push(davReq(f, 'GET', url, { Range: 'bytes=' + off + '-' + (off + len - 1) }, null, len + 65536, function (err, sc, buf) {
1777
+ if (err) { cb(err); return; }
1778
+ if (sc !== 206 && !(sc === 200 && off === 0)) { cb(upError('HTTP ' + sc, 502)); return; }
1779
+ cb(null, buf.length > len ? buf.slice(0, len) : buf, 0);
1780
+ }));
1781
+ };
1782
+ }
1783
+
1784
+ // /fsmi: a video's header on a USB drive.
1785
+ function fsMediaInfo(p, cb) {
1786
+ miFileReader(p, function (err, readAt, done) {
1787
+ if (err) { cb(err); return; }
1788
+ mediaInfo(readAt, function (e, r) { done(); cb(e, r); });
1789
+ });
1790
+ }
1356
1791
  // ---- Downloads to a USB drive ----
1357
1792
  // StremioK asks (/fsdl/add: a link, the folder on a drive, the file's name); one at a time, the
1358
1793
  // rest wait. Into "<name>.part", renamed when complete. A dropped connection is picked up where
@@ -1770,6 +2205,84 @@ function dlRun(e) {
1770
2205
  }
1771
2206
  }
1772
2207
 
2208
+ // ---- Backup and logs on a USB drive: /bak/write (POST), /bak/read ----
2209
+ // For when the phone's page can't be reached: Export configuration's file and Diagnostics' logs
2210
+ // written to a USB drive StremioK lists (a mounted one under /opt/media), and the backup read back.
2211
+ // Only into its StremioK folder, under two names: stremiok-backup.txt (replaced each time) and
2212
+ // stremiok-logs-<date and time>.txt; BAK_MAX at most. Written in full to a .part file, flushed to
2213
+ // the drive, then renamed (a stick pulled meanwhile leaves the last backup whole). Nothing else
2214
+ // is read or written: no path comes from the page but the drive's.
2215
+ var BAK_MAX = 1572864, BAK_DIR = 'StremioK', BAK_FILE = 'stremiok-backup.txt';
2216
+ function bakDrive(q) {
2217
+ var d = String(q.drive || '');
2218
+ if (!/^\/opt\/media\/[^\/]+$/.test(d) || !fsDirOk(d) || !isMounted(d)) { return null; }
2219
+ return d;
2220
+ }
2221
+ function bakName(kind) {
2222
+ if (kind === 'backup') { return BAK_FILE; }
2223
+ var t = new Date(Date.now()), two = function (n) { return (n < 10 ? '0' : '') + n; };
2224
+ return 'stremiok-logs-' + t.getFullYear() + '-' + two(t.getMonth() + 1) + '-' + two(t.getDate()) + '-' + two(t.getHours()) + two(t.getMinutes()) + two(t.getSeconds()) + '.txt';
2225
+ }
2226
+ function bakWrite(drive, kind, text, cb) {
2227
+ cb = once(cb);
2228
+ var fs = require('fs'), dir = drive + '/' + BAK_DIR, name = bakName(kind), data = toBuffer(text);
2229
+ if (data.length > BAK_MAX) { cb({ status: 413, message: 'too much' }); return; }
2230
+ fs.mkdir(dir, function (e0) {
2231
+ if (e0 && e0.code !== 'EEXIST') { cb({ status: errStatus(e0), message: e0.code || e0.message }); return; }
2232
+ fsRealOk(dir, function (err, realDir) { // (StremioK's folder, not a link out of the drive)
2233
+ if (err) { cb(err); return; }
2234
+ fs.lstat(realDir, function (e1, st) {
2235
+ if (e1 || !st || !st.isDirectory()) { cb({ status: 409, message: 'not a folder' }); return; }
2236
+ var part = realDir + '/' + name + '.part', dest = realDir + '/' + name;
2237
+ fs.open(part, 'w', function (e2, fd) {
2238
+ if (e2) { cb({ status: errStatus(e2), message: e2.code || e2.message }); return; }
2239
+ fs.write(fd, data, 0, data.length, 0, function (e3) {
2240
+ fs.fsync(fd, function () {
2241
+ fs.close(fd, function () {
2242
+ if (e3) { fs.unlink(part, function () {}); cb({ status: 507, message: e3.code || e3.message }); return; }
2243
+ fs.rename(part, dest, function (e4) {
2244
+ if (e4) { fs.unlink(part, function () {}); cb({ status: errStatus(e4), message: e4.code || e4.message }); return; }
2245
+ cb(null, { file: BAK_DIR + '/' + name, size: data.length });
2246
+ });
2247
+ });
2248
+ });
2249
+ });
2250
+ });
2251
+ });
2252
+ });
2253
+ });
2254
+ }
2255
+ function bakRead(drive, cb) {
2256
+ cb = once(cb);
2257
+ var fs = require('fs'), p = drive + '/' + BAK_DIR + '/' + BAK_FILE;
2258
+ fsRealOk(p, function (err, real) {
2259
+ if (err) { cb(err.status === 404 || /ENOENT/.test(err.message || '') ? { status: 404, message: 'no backup on that drive' } : err); return; }
2260
+ fs.open(real, 'r', function (e0, fd) {
2261
+ if (e0) { cb({ status: 404, message: 'no backup on that drive' }); return; }
2262
+ fs.fstat(fd, function (e1, st) {
2263
+ if (e1 || !st || !st.isFile()) { fs.close(fd, function () {}); cb({ status: 404, message: 'no backup on that drive' }); return; }
2264
+ if (st.size > BAK_MAX) { fs.close(fd, function () {}); cb({ status: 413, message: 'too large to be a backup' }); return; }
2265
+ var buf = allocBuffer(st.size);
2266
+ fs.read(fd, buf, 0, st.size, 0, function (e2, n) {
2267
+ fs.close(fd, function () {});
2268
+ if (e2) { cb({ status: 500, message: e2.code || e2.message }); return; }
2269
+ cb(null, { text: buf.slice(0, n).toString('utf8'), at: st.mtime ? +st.mtime : 0 });
2270
+ });
2271
+ });
2272
+ });
2273
+ });
2274
+ }
2275
+ function bakControl(req, res, path, query, body) {
2276
+ var q = davQ(query), drive = bakDrive(q);
2277
+ if (!drive) { send(res, 400, 'text/plain', 'not a USB drive'); return; }
2278
+ function answer(err, r) {
2279
+ if (err) { send(res, err.status && err.status < 600 ? err.status : 500, 'text/plain', 'failed: ' + (err.message || 'unknown')); return; }
2280
+ send(res, 200, 'application/json', JSON.stringify(r));
2281
+ }
2282
+ if (path === '/bak/write') { bakWrite(drive, q.kind === 'logs' ? 'logs' : 'backup', body, answer); return; }
2283
+ bakRead(drive, answer);
2284
+ }
2285
+
1773
2286
  // ---- HTTP ----
1774
2287
  function send(res, code, type, body) {
1775
2288
  try {
@@ -1801,20 +2314,21 @@ function handle(req, res) {
1801
2314
  // The app's own guide POSTs: a browser sends an Origin with every POST (the app's page is
1802
2315
  // file://: "null"); let through with the token, or the guide ticket (for an app that can't
1803
2316
  // read the token: see /epg/ticket), which no web page has (/epg/ only).
1804
- if (who === 'origin' && req.method === 'POST' && /^\/(epg\/(load|get|clear)|drm\/license|entry\/give|plug\/fetch)$/.test(path) && /^(null|file:\/\/)$/.test(String(req.headers.origin || '')) && (hasToken(parts[1]) || hasTicket(parts[1]))) { who = null; } // (and a DRM license's: see drmControl)
2317
+ if (who === 'origin' && req.method === 'POST' && /^\/(epg\/(load|get|clear)|drm\/license|entry\/give|plug\/fetch|bak\/write)$/.test(path) && /^(null|file:\/\/)$/.test(String(req.headers.origin || '')) && (hasToken(parts[1]) || hasTicket(parts[1]))) { who = null; } // (and a DRM license's: see drmControl)
1805
2318
  if (who) { send(res, 403, 'text/plain', 'not allowed (' + who + ')'); return; }
1806
2319
  if (req.method === 'OPTIONS') { if (isFs) { send(res, 403, 'text/plain', 'not allowed'); return; } res.writeHead(200); res.end(); return; }
1807
2320
  var epgPost = req.method === 'POST' && /^\/epg\/(load|get|clear)$/.test(path); // (a guide's channels: in the body, see epgControl)
1808
2321
  var drmPost = req.method === 'POST' && path === '/drm/license'; // (a Widevine license request: see drmControl)
1809
2322
  var givePost = req.method === 'POST' && path === '/entry/give'; // (a configuration file for the phone: see entryControl)
1810
2323
  var plugPost = req.method === 'POST' && path === '/plug/fetch'; // (a Nuvio plugin's request: see plugControl)
1811
- if (req.method !== 'GET' && !epgPost && !drmPost && !givePost && !plugPost) { send(res, 405, 'text/plain', 'GET only'); return; } // (before any work)
1812
- if (req.url.length > (/^\/epg\//.test(path) ? 32768 : /^\/(fsdl\/add|live\/(open|master)|dav\/(list|walk|sub))$/.test(path) ? 8192 : 2048)) { send(res, 414, 'text/plain', 'request too long'); return; } // (a download's link can be long; a guide's channels, a bitset)
2324
+ var bakPost = req.method === 'POST' && path === '/bak/write'; // (a backup or the logs for a USB drive: see bakControl)
2325
+ if (req.method !== 'GET' && !epgPost && !drmPost && !givePost && !plugPost && !bakPost) { send(res, 405, 'text/plain', 'GET only'); return; } // (before any work)
2326
+ if (req.url.length > (/^\/epg\//.test(path) ? 32768 : /^\/(fsdl\/add|live\/(open|master)|dav\/(list|walk|sub|mi|open)|smb\/[a-z]+|dlna\/[a-z]+)$/.test(path) ? 8192 : 2048)) { send(res, 414, 'text/plain', 'request too long'); return; } // (a download's link can be long; a guide's channels, a bitset)
1813
2327
  // (StremioK gave up on it — a screen left, the player closed: what it still waits for is
1814
2328
  // dropped; 'close' before the response finished means that on every Node)
1815
2329
  var leaving = [];
1816
2330
  function leaveAll() { var l = leaving; leaving = []; l.forEach(function (f) { try { f(); } catch (e) {} }); }
1817
- if (!isFs && path !== '/dav/walk' && !/^\/live\/[0-9a-f]{32}\/[tf]$/.test(path)) { // (a folder's walk, a raw channel's or a file's stream: their own limits)
2331
+ if (!isFs && path !== '/dav/walk' && path !== '/smb/walk' && path !== '/dlna/walk' && !/^\/live\/[0-9a-f]{32}\/[tf]$/.test(path) && !/^\/net\/[0-9a-f]{32}\/f$/.test(path)) { // (a folder's walk, a raw channel's or a file's stream: their own limits)
1818
2332
  var deadline = setTimeout(function () { if (!res.headersSent) { send(res, 504, 'text/plain', 'took too long'); } leaveAll(); }, REQ_MS);
1819
2333
  res.on('finish', function () { clearTimeout(deadline); });
1820
2334
  res.on('close', function () { clearTimeout(deadline); if (!res.finished) { leaveAll(); } });
@@ -1828,6 +2342,16 @@ function handle(req, res) {
1828
2342
  req.on('end', function () { if (!gover) { entryControl(req, res, path, parts[1], gbody); } });
1829
2343
  return;
1830
2344
  }
2345
+ if (bakPost || path === '/bak/read') {
2346
+ if (!entryAllowed(req, parts[1]) && !(bakPost && hasTicket(parts[1]))) { send(res, 403, 'text/plain', 'not allowed (token)'); req.resume(); return; }
2347
+ if (!bakPost) { bakControl(req, res, path, parts[1], ''); return; }
2348
+ if (+(req.headers['content-length'] || 0) > BAK_MAX) { send(res, 413, 'text/plain', 'too much'); req.resume(); return; }
2349
+ var bbody = '', bover = false;
2350
+ req.setEncoding('utf8');
2351
+ req.on('data', function (c) { if (bover) { return; } bbody += c; if (bbody.length > BAK_MAX) { bover = true; send(res, 413, 'text/plain', 'too much'); } });
2352
+ req.on('end', function () { if (!bover) { bakControl(req, res, path, parts[1], bbody); } });
2353
+ return;
2354
+ }
1831
2355
  if (/^\/entry\//.test(path)) { entryControl(req, res, path, parts[1]); return; }
1832
2356
  if (/^\/live\//.test(path)) { liveControl(req, res, path, parts[1], leaving); return; }
1833
2357
  if (epgPost) { // what's asked, in the body (to EPG_BODY_MAX), after the address's own (its token)
@@ -1857,7 +2381,10 @@ function handle(req, res) {
1857
2381
  return;
1858
2382
  }
1859
2383
  if (/^\/epg\//.test(path)) { epgControl(req, res, path, parts[1]); return; } // (a playlist's TV guide: see epgControl)
1860
- if (/^\/dav\//.test(path)) { davControl(req, res, path, parts[1], leaving); return; } // (a network folder: see davControl)
2384
+ if (/^\/dav\//.test(path)) { davControl(req, res, path, parts[1], leaving); return; }
2385
+ if (/^\/net\//.test(path)) { netControl(req, res, path, parts[1]); return; }
2386
+ if (/^\/smb\//.test(path)) { smbControl(req, res, path, parts[1], leaving); return; } // (a Windows / NAS share: see smbControl)
2387
+ if (/^\/dlna\//.test(path)) { dlnaControl(req, res, path, parts[1], leaving); return; } // (a DLNA media server: see dlnaControl) // (a network folder's file, for the player: its ticket) // (a network folder: see davControl)
1861
2388
  if (path === '/aiom/addons') { aiomControl(req, res, parts[1], leaving); return; }
1862
2389
  if (path === '/xtvod/list' || path === '/xtvod/find') { xtvControl(req, res, path, parts[1]); return; } // (an Xtream account's films and series: see xtvControl)
1863
2390
  if (path === '/stalker/list' || path === '/stalker/link' || path === '/stalker/genres' || path === '/stalker/vod' || path === '/stalker/play') { stalkerControl(req, res, path, parts[1], leaving); return; } // (a Stalker portal: see stalkerControl) // (AIOManager's addons: see aiomControl) // (a live channel's sound repacked: see liveControl) // (the phone's one-time page: see below)
@@ -1877,13 +2404,13 @@ function handle(req, res) {
1877
2404
  return;
1878
2405
  }
1879
2406
  if (isFs) {
1880
- if (['/fslist', '/fswalk', '/fssub', '/fshash'].indexOf(path) === -1) { send(res, 404, 'text/plain', 'not found'); return; }
2407
+ if (['/fslist', '/fswalk', '/fssub', '/fshash', '/fsmi'].indexOf(path) === -1) { send(res, 404, 'text/plain', 'not found'); return; }
1881
2408
  var why = fsAllowed(req, parts[1]);
1882
2409
  if (why) { send(res, 403, 'text/plain', 'not allowed (' + why + ')'); return; }
1883
2410
  var fm = (parts[1] || '').match(/(?:^|&)path=([^&]*)/), fp = '';
1884
2411
  try { fp = fm ? decodeURIComponent(fm[1]) : ''; } catch (e) { fp = ''; }
1885
2412
  if (!fsDirOk(fp)) { send(res, 400, 'text/plain', 'not on a USB drive'); return; }
1886
- var job = path === '/fslist' ? fsList : path === '/fswalk' ? fsWalk : path === '/fssub' ? fsSub : fsHash;
2413
+ var job = path === '/fslist' ? fsList : path === '/fswalk' ? fsWalk : path === '/fssub' ? fsSub : path === '/fsmi' ? fsMediaInfo : fsHash;
1887
2414
  var waiting = job(fp, function (err, r) {
1888
2415
  if (err) { send(res, err.status || 500, 'text/plain', 'failed: ' + (err.message || 'unknown')); return; }
1889
2416
  if (path === '/fssub') { send(res, 200, 'text/plain; charset=utf-8', r); return; }
@@ -2918,6 +3445,18 @@ function liveControl(req, res, path, query, leaving) {
2918
3445
  }, leaving);
2919
3446
  return;
2920
3447
  }
3448
+ if (path === '/live/mi') { // what's in a source's file, from its header (see mediaInfo)
3449
+ if (!entryAllowed(req, query)) { send(res, 403, 'text/plain', 'not allowed (token)'); return; }
3450
+ var iu = q.u || '', stops = [];
3451
+ if (!/^https?:\/\/[^\s]+$/i.test(iu) || iu.length > 2000) { send(res, 400, 'text/plain', 'bad link'); return; }
3452
+ var stopMi = mediaInfo(miHttpReader(iu, liveWho(q), q.lan === '1', stops), function (err, r) {
3453
+ stops.forEach(function (f) { try { f(); } catch (e) {} });
3454
+ if (err) { send(res, err.status && err.status < 600 ? err.status : 502, 'text/plain', 'failed: ' + (err.message || 'unknown')); return; }
3455
+ send(res, 200, 'application/json', JSON.stringify(r));
3456
+ });
3457
+ if (stopMi) { leaving.push(stopMi); }
3458
+ return;
3459
+ }
2921
3460
  if (path === '/live/file') { // a file through the relay (see liveFile)
2922
3461
  if (!entryAllowed(req, query)) { send(res, 403, 'text/plain', 'not allowed (token)'); return; }
2923
3462
  var fu = q.u || '';
@@ -3079,8 +3618,54 @@ function davFolder(req, q) {
3079
3618
  if (a && !/^[A-Za-z0-9+\/=]{4,1400}$/.test(a)) { return null; }
3080
3619
  if (c && !/^[A-Za-z0-9+\/=]{200,5000}$/.test(c)) { return null; }
3081
3620
  var pem = c ? '-----BEGIN CERTIFICATE-----\n' + c.replace(/(.{64})/g, '$1\n').replace(/\n$/, '') + '\n-----END CERTIFICATE-----\n' : '';
3082
- return { base: base, pu: urllib.parse(base), auth: a ? 'Basic ' + a : '', cert: pem };
3621
+ var up = a ? fromBase64(a).toString('utf8') : '', colon = up.indexOf(':');
3622
+ return { base: base, pu: urllib.parse(base), auth: a ? 'Basic ' + a : '', cert: pem, user: colon === -1 ? up : up.slice(0, colon), pass: colon === -1 ? '' : up.slice(colon + 1) };
3623
+ }
3624
+ // Digest sign-in (RFC 7616, MD5 and MD5-sess, qop=auth): a folder whose server asks for it in its
3625
+ // 401 (some NAS and router firmwares offer nothing else). Its challenge kept here, in memory, per
3626
+ // folder and sign-in (DAV_DIGEST_MAX), so the next requests send it at once (no 401 round trip
3627
+ // each); a stale or new challenge replaces it. Adapted from Tessel's (MIT License, Copyright (c)
3628
+ // 2026 Patrick: github.com/PatrickSt1991/tessel-tizen-tv).
3629
+ var DAV_DIGEST_MAX = 16, _davDigest = {};
3630
+ function davDigestKey(f) { return f.base + '\n' + crypto.createHash('sha256').update(f.auth || '').digest('hex'); }
3631
+ function md5hex(s) { return crypto.createHash('md5').update(toBuffer(String(s), 'utf8')).digest('hex'); }
3632
+ function davChallenge(h) {
3633
+ var m = /(^|[\s,])digest\s+([\s\S]*)/i.exec(String(h || ''));
3634
+ if (!m) { return null; }
3635
+ var d = {}, re = /([a-z0-9_-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]+))/gi, p, n = 0;
3636
+ while ((p = re.exec(m[2])) && n++ < 20) { d[p[1].toLowerCase()] = (p[2] !== undefined ? p[2].replace(/\\(.)/g, '$1') : p[3]).slice(0, 500); }
3637
+ if (d.realm === undefined || !d.nonce) { return null; }
3638
+ var alg = String(d.algorithm || 'MD5').toUpperCase();
3639
+ if (alg !== 'MD5' && alg !== 'MD5-SESS') { return null; } // (SHA-256 Digest: not offered by the servers seen)
3640
+ return d;
3641
+ }
3642
+ function davDigestAuth(f, method, uri) {
3643
+ var k = davDigestKey(f), st = _davDigest[k];
3644
+ if (!st || !f.auth) { return ''; }
3645
+ var ch = st.ch, alg = String(ch.algorithm || 'MD5').toUpperCase(), cnonce = crypto.randomBytes(8).toString('hex');
3646
+ st.nc++;
3647
+ var ha1 = md5hex(f.user + ':' + ch.realm + ':' + f.pass);
3648
+ if (alg === 'MD5-SESS') { ha1 = md5hex(ha1 + ':' + ch.nonce + ':' + cnonce); }
3649
+ var ha2 = md5hex(method + ':' + uri), qop = /(^|,)\s*auth\s*(,|$)/i.test(ch.qop || '') ? 'auth' : '';
3650
+ var nc = ('00000000' + st.nc.toString(16)).slice(-8);
3651
+ var resp = qop ? md5hex(ha1 + ':' + ch.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2) : md5hex(ha1 + ':' + ch.nonce + ':' + ha2);
3652
+ var q = function (v) { return '"' + String(v).replace(/["\\]/g, '\\$&') + '"'; };
3653
+ var out = 'Digest username=' + q(f.user) + ', realm=' + q(ch.realm) + ', nonce=' + q(ch.nonce) + ', uri=' + q(uri) + ', response="' + resp + '", algorithm=' + (alg === 'MD5-SESS' ? 'MD5-sess' : 'MD5');
3654
+ if (qop) { out += ', qop=auth, nc=' + nc + ', cnonce="' + cnonce + '"'; }
3655
+ if (ch.opaque) { out += ', opaque=' + q(ch.opaque); }
3656
+ return out;
3083
3657
  }
3658
+ function davDigestLearn(f, header) {
3659
+ var ch = f.auth ? davChallenge(header) : null;
3660
+ if (!ch) { return false; }
3661
+ var k = davDigestKey(f), keys = Object.keys(_davDigest);
3662
+ if (!_davDigest[k] && keys.length >= DAV_DIGEST_MAX) { delete _davDigest[keys[0]]; }
3663
+ _davDigest[k] = { ch: ch, nc: 0 };
3664
+ return true;
3665
+ }
3666
+ function davUsesDigest(f) { return !!_davDigest[davDigestKey(f)]; }
3667
+ // The sign-in a request to the folder carries: Digest once its server asked for it, else Basic.
3668
+ function davAuthFor(f, method, path) { return davDigestAuth(f, method, path) || f.auth; }
3084
3669
  // A path under the folder (each part %-escaped; '', '.' and '..' refused), or null.
3085
3670
  function davUrl(f, rel, dir) {
3086
3671
  rel = String(rel || '').replace(/^\/+|\/+$/g, '');
@@ -3105,7 +3690,7 @@ function davReq(f, method, url, headers, body, max, cb) {
3105
3690
  if ((pu.protocol !== 'http:' && pu.protocol !== 'https:') || !dlHostOk(pu.hostname)) { finish(upError('an address it can\'t reach', 400)); return; }
3106
3691
  var h = { 'User-Agent': 'StremioK', 'Accept': '*/*' }, data = body ? toBuffer(body) : null;
3107
3692
  Object.keys(headers || {}).forEach(function (k) { h[k] = headers[k]; });
3108
- if (f.auth) { h.Authorization = f.auth; }
3693
+ if (f.auth) { h.Authorization = davAuthFor(f, method, pu.path); }
3109
3694
  if (data) { h['Content-Length'] = data.length; }
3110
3695
  var opts = { hostname: pu.hostname, port: pu.port, path: pu.path, method: method, headers: h };
3111
3696
  if (pu.protocol === 'https:') {
@@ -3125,6 +3710,8 @@ function davReq(f, method, url, headers, body, max, cb) {
3125
3710
  go(urllib.format(np), hops + 1);
3126
3711
  return;
3127
3712
  }
3713
+ // (a Digest challenge, new or stale: answered once with it)
3714
+ if (sc === 401 && !ctl.digested && davDigestLearn(f, resp.headers['www-authenticate'])) { resp.resume(); ctl.digested = true; go(u, hops); return; }
3128
3715
  if (sc < 200 || sc >= 300) { resp.resume(); finish(null, sc, null, u); return; }
3129
3716
  resp.on('data', function (c) { if (ctl.done) { return; } chunks.push(c); size += c.length; if (size > max) { finish(davWhy('toolarge', 'its answer is over ' + Math.round(max / 1048576) + ' MB')); } });
3130
3717
  resp.on('end', function () { finish(null, sc, Buffer.concat(chunks, size), u); });
@@ -3217,7 +3804,7 @@ function davList(f, rel, cb) {
3217
3804
  if (sc !== 207 || !/multistatus/i.test(text)) { cb(davWhy('notdav', 'not a WebDAV folder (HTTP ' + sc + ')')); return; }
3218
3805
  var dirPath = '/';
3219
3806
  try { dirPath = String(urllib.parse(at).pathname || '/'); dirPath = decodeURIComponent(dirPath); } catch (e) {}
3220
- cb(null, { entries: davEntries(text, dirPath) });
3807
+ cb(null, { entries: davEntries(text, dirPath), digest: davUsesDigest(f) || undefined }); // (digest: plays through the service, see /net/)
3221
3808
  });
3222
3809
  }
3223
3810
  // Every video and subtitle file under the folder (the index): cb(err, { files: [{ p, size }],
@@ -3239,11 +3826,12 @@ function davWalk(f, st, cb) {
3239
3826
  if (!d.rel) { st.cancelled = true; cb(err); return; } // (the folder itself)
3240
3827
  truncated = true;
3241
3828
  } else {
3829
+ var names = r.entries.map(function (e) { return e.name; });
3242
3830
  r.entries.forEach(function (e) {
3243
3831
  if (HIDDEN_NAME.test(e.name)) { return; }
3244
3832
  var p = d.rel ? d.rel + '/' + e.name : e.name;
3245
3833
  if (e.dir) { if (d.depth < DAV_WALK_DEPTH) { queue.push({ rel: p, depth: d.depth + 1 }); } else { truncated = true; } }
3246
- else if ((VIDEO_EXT.test(e.name) || SUB_EXT.test(e.name)) && files.length < DAV_WALK_FILES) { files.push({ p: p, size: e.size || 0 }); }
3834
+ else if (walkWants(e.name, names) && files.length < DAV_WALK_FILES) { files.push({ p: p, size: e.size || 0 }); }
3247
3835
  });
3248
3836
  }
3249
3837
  pump();
@@ -3263,8 +3851,1005 @@ function davSub(f, rel, cb) {
3263
3851
  if (err) { cb(err); return; }
3264
3852
  if (sc !== 200 || !buf) { cb(upError('HTTP ' + sc, 502)); return; }
3265
3853
  var text = decodeText(buf);
3266
- cb(null, /\.(ass|ssa)$/i.test(String(rel)) ? assToSrt(text) : text);
3854
+ cb(null, text);
3855
+ });
3856
+ }
3857
+ // ---- Windows / NAS shares (SMB): /smb/shares, /smb/list, /smb/walk, /smb/sub, /smb/mi, /smb/open ----
3858
+ // A share as a network folder: listed, indexed, its subtitle files read and its files played (through
3859
+ // /net/<ticket>/f: the player's byte ranges as SMB reads). The client: SMB 2.0.2 / 2.1 (no SMB 1, no
3860
+ // SMB 3 encryption), NTLMv2 sign-in or guest, HMAC-SHA256 signing where the server wants it (or the
3861
+ // session isn't a guest's), CREATE / QUERY_DIRECTORY / READ / CLOSE, and the share list through
3862
+ // the srvsvc pipe (NetrShareEnum). Adapted from Tessel's (MIT License, Copyright (c) 2026 Patrick:
3863
+ // github.com/PatrickSt1991/tessel-tizen-tv, tizen-app/service/service.js), every length and offset a
3864
+ // server sends checked against what came (a broken or hostile one can't make it throw, allocate or
3865
+ // wait for ever): SMB_MSG_MAX a message, SMB_REQ_MS a request, SMB_CONN_MAX connections, closed
3866
+ // SMB_IDLE_MS unused. Only to the home network (a private address, or a name in it: isLanName).
3867
+ // The sign-in comes with each request (X-Dav-Auth: user:password, "DOMAIN\user" for a domain; none:
3868
+ // a guest) and is kept only with an open connection or a player's ticket.
3869
+ var SMB_PORT = 445, SMB_CONNECT_MS = 8000, SMB_REQ_MS = 15000, SMB_IDLE_MS = 120000, SMB_CONN_MAX = 4, SMB_MSG_MAX = 8 * 1048576;
3870
+ var SMB_READ = 262144, SMB_LIST_MAX = 3000, SMB_WALK_DIRS = 2000, SMB_WALK_FILES = 20000, SMB_WALK_DEPTH = 12, SMB_WALK_MS = 90000, SMB_SUB_MAX = 5 * 1048576;
3871
+ var SMB2 = { NEGOTIATE: 0, SESSION_SETUP: 1, TREE_CONNECT: 3, CREATE: 5, CLOSE: 6, READ: 8, IOCTL: 0x0B, QUERY_DIRECTORY: 0x0E };
3872
+ var SMB_ST = { SUCCESS: 0, MORE_PROCESSING: 0xC0000016, NO_MORE_FILES: 0x80000006, END_OF_FILE: 0xC0000011, BUFFER_OVERFLOW: 0x80000005, PENDING: 0x00000103 };
3873
+ // The statuses a person can do something about: [why (the app's wording), what it means].
3874
+ var SMB_STATUS = {
3875
+ 0xc0000022: ['auth', 'this account isn\'t allowed in here'], 0xc0000064: ['auth', 'no such user on the server'], 0xc000006a: ['auth', 'wrong password'],
3876
+ 0xc000006d: ['auth', 'wrong user name or password'], 0xc000006f: ['auth', 'this account may not sign in at this hour'], 0xc0000070: ['auth', 'the server refuses sign-ins from this device'],
3877
+ 0xc0000071: ['auth', 'that password has expired'], 0xc0000072: ['auth', 'that account is disabled'], 0xc000015b: ['auth', 'this account may not sign in over the network'],
3878
+ 0xc0000234: ['auth', 'that account is locked out'], 0xc00000bb: ['smb3', 'the server refused (it may want SMB 3, or NTLM is off)'],
3879
+ 0xc00000cc: ['missing', 'no share with that name on the server'], 0xc0000034: ['missing', 'no such file or folder'], 0xc000003a: ['missing', 'no such folder'],
3880
+ 0xc0000043: ['other', 'the file is in use by another program'], 0xc0000203: ['other', 'the server ended the session']
3881
+ };
3882
+ function smbErr(status, what) {
3883
+ var e = SMB_STATUS[status >>> 0], hex = '0x' + ((status >>> 0).toString(16));
3884
+ var err = new Error((what ? what + ': ' : '') + (e ? e[1] : status === -1 ? 'the connection dropped' : 'status ' + hex));
3885
+ err.why = e ? e[0] : status === -1 ? 'unreachable' : 'other';
3886
+ err.status = e && e[0] === 'missing' ? 404 : 502;
3887
+ return err;
3888
+ }
3889
+ // Strings and numbers as SMB has them (by hand: the 2017 TV's Buffer lacks some encodings).
3890
+ function smbU16(str) { str = String(str == null ? '' : str); var b = allocBuffer(str.length * 2); for (var i = 0; i < str.length; i++) { b.writeUInt16LE(str.charCodeAt(i) & 0xFFFF, i * 2); } return b; }
3891
+ function smbFromU16(buf, start, end) { var s = ''; end = Math.min(end, buf.length); for (var i = start; i + 1 < end; i += 2) { s += String.fromCharCode(buf.readUInt16LE(i)); } return s; }
3892
+ function smbAscii(str) { var b = allocBuffer(str.length); for (var i = 0; i < str.length; i++) { b[i] = str.charCodeAt(i) & 0xFF; } return b; }
3893
+ function smbBytes(arr) { var b = allocBuffer(arr.length); for (var i = 0; i < arr.length; i++) { b[i] = arr[i] & 0xFF; } return b; }
3894
+ function smbW64(b, off, n) { b.writeUInt32LE(n % 4294967296 >>> 0, off); b.writeUInt32LE(Math.floor(n / 4294967296) >>> 0, off + 4); }
3895
+ function smbR64(b, off) { return b.readUInt32LE(off) + b.readUInt32LE(off + 4) * 4294967296; }
3896
+ function smbFill(n, v) { var b = allocBuffer(n); b.fill(v || 0); return b; }
3897
+ // MD4 (RFC 1320), for the NT hash: the TV's OpenSSL may not have it.
3898
+ function md4(buf) {
3899
+ function rol(x, n) { return (x << n) | (x >>> (32 - n)); }
3900
+ function F(x, y, z) { return (x & y) | (~x & z); }
3901
+ function G(x, y, z) { return (x & y) | (x & z) | (y & z); }
3902
+ function Hh(x, y, z) { return x ^ y ^ z; }
3903
+ var len = buf.length, withPad = len + 1;
3904
+ while (withPad % 64 !== 56) { withPad++; }
3905
+ var m = smbFill(withPad + 8);
3906
+ buf.copy(m, 0); m[len] = 0x80;
3907
+ m.writeUInt32LE((len * 8) >>> 0, withPad); m.writeUInt32LE(Math.floor(len * 8 / 4294967296) >>> 0, withPad + 4);
3908
+ var a = 0x67452301, b = 0xefcdab89, c = 0x98badcfe, d = 0x10325476, X = [], i, k, t;
3909
+ var R2 = [0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15], R3 = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15];
3910
+ var S1 = [3, 7, 11, 19], S2 = [3, 5, 9, 13], S3 = [3, 9, 11, 15];
3911
+ for (var off = 0; off < m.length; off += 64) {
3912
+ for (i = 0; i < 16; i++) { X[i] = m.readUInt32LE(off + i * 4); }
3913
+ var aa = a, bb = b, cc = c, dd = d;
3914
+ for (i = 0; i < 48; i++) {
3915
+ var r = i >> 4, j = i & 15, f, s;
3916
+ if (r === 0) { k = j; s = S1[j & 3]; } else if (r === 1) { k = R2[j]; s = S2[j & 3]; } else { k = R3[j]; s = S3[j & 3]; }
3917
+ var add = r === 0 ? 0 : r === 1 ? 0x5a827999 : 0x6ed9eba1;
3918
+ var w = j & 3;
3919
+ var x0 = w === 0 ? a : w === 1 ? d : w === 2 ? c : b, x1 = w === 0 ? b : w === 1 ? a : w === 2 ? d : c, x2 = w === 0 ? c : w === 1 ? b : w === 2 ? a : d, x3 = w === 0 ? d : w === 1 ? c : w === 2 ? b : a;
3920
+ f = r === 0 ? F(x1, x2, x3) : r === 1 ? G(x1, x2, x3) : Hh(x1, x2, x3);
3921
+ t = rol((x0 + f + X[k] + add) | 0, s);
3922
+ if (w === 0) { a = t; } else if (w === 1) { d = t; } else if (w === 2) { c = t; } else { b = t; }
3923
+ }
3924
+ a = (a + aa) | 0; b = (b + bb) | 0; c = (c + cc) | 0; d = (d + dd) | 0;
3925
+ }
3926
+ var out = allocBuffer(16);
3927
+ out.writeUInt32LE(a >>> 0, 0); out.writeUInt32LE(b >>> 0, 4); out.writeUInt32LE(c >>> 0, 8); out.writeUInt32LE(d >>> 0, 12);
3928
+ return out;
3929
+ }
3930
+ function hmacMd5(key, data) { return crypto.createHmac('md5', key).update(data).digest(); }
3931
+ var NTLM_FLAGS = (0x00000001 | 0x00000004 | 0x00000010 | 0x00000200 | 0x00008000 | 0x00080000 | 0x20000000 | 0x80000000) >>> 0, NTLM_ANON = 0x00000800;
3932
+ function ntlmNegotiate() { var b = smbFill(32); smbAscii('NTLMSSP\0').copy(b, 0); b.writeUInt32LE(1, 8); b.writeUInt32LE(NTLM_FLAGS, 12); return b; }
3933
+ function ntlmAvPair(ti, id) { // an AV pair's value in target info, or null
3934
+ for (var p = 0; p + 4 <= ti.length;) {
3935
+ var aid = ti.readUInt16LE(p), alen = ti.readUInt16LE(p + 2);
3936
+ if (aid === 0 || p + 4 + alen > ti.length) { return null; }
3937
+ if (aid === id) { return ti.slice(p + 4, p + 4 + alen); }
3938
+ p += 4 + alen;
3939
+ }
3940
+ return null;
3941
+ }
3942
+ function ntlmWithMicFlag(ti) { // MsvAvFlags with "MIC present" (0x2), added before MsvAvEOL if missing
3943
+ var p = 0, eol = ti.length;
3944
+ while (p + 4 <= ti.length) {
3945
+ var id = ti.readUInt16LE(p), len = ti.readUInt16LE(p + 2);
3946
+ if (id === 0 || p + 4 + len > ti.length) { eol = p; break; }
3947
+ if (id === 6 && len === 4) { var out = smbFill(ti.length); ti.copy(out); out.writeUInt32LE((out.readUInt32LE(p + 4) | 2) >>> 0, p + 4); return out; }
3948
+ p += 4 + len;
3949
+ }
3950
+ var pair = smbFill(8); pair.writeUInt16LE(6, 0); pair.writeUInt16LE(4, 2); pair.writeUInt32LE(2, 4);
3951
+ return Buffer.concat([ti.slice(0, eol), pair, smbFill(4)]);
3952
+ }
3953
+ function ntlmField(len, off) { var f = smbFill(8); f.writeUInt16LE(len, 0); f.writeUInt16LE(len, 2); f.writeUInt32LE(off, 4); return f; }
3954
+ function ntlmAuthenticate(challenge, user, pass, domain) {
3955
+ if (challenge.length < 48 || smbAscii('NTLMSSP\0').toString('hex') !== challenge.slice(0, 8).toString('hex') || challenge.readUInt32LE(8) !== 2) { throw new Error('not an NTLM challenge'); }
3956
+ var serverChallenge = challenge.slice(24, 32), tiLen = challenge.readUInt16LE(40), tiOff = challenge.readUInt32LE(44);
3957
+ if (tiOff + tiLen > challenge.length) { throw new Error('a broken NTLM challenge'); }
3958
+ var ti = challenge.slice(tiOff, tiOff + tiLen), ts = ntlmAvPair(ti, 7), haveTs = !!(ts && ts.length === 8);
3959
+ var key = hmacMd5(md4(smbU16(pass)), smbU16(String(user).toUpperCase() + domain)), cc = crypto.randomBytes(8);
3960
+ var blob = Buffer.concat([smbBytes([1, 1, 0, 0, 0, 0, 0, 0]), haveTs ? ts : smbFill(8), cc, smbFill(4), haveTs ? ntlmWithMicFlag(ti) : ti, smbFill(4)]);
3961
+ var proof = hmacMd5(key, Buffer.concat([serverChallenge, blob])), nt = Buffer.concat([proof, blob]);
3962
+ var lm = haveTs ? smbFill(24) : Buffer.concat([hmacMd5(key, Buffer.concat([serverChallenge, cc])), cc]);
3963
+ var sessionKey = hmacMd5(key, proof), dom = smbU16(domain), usr = smbU16(user), ws = smbU16('STREMIOK');
3964
+ var fixed = 88, cur = fixed, lmOff = cur; cur += lm.length;
3965
+ var ntOff = cur; cur += nt.length; var domOff = cur; cur += dom.length; var userOff = cur; cur += usr.length; var wsOff = cur; cur += ws.length;
3966
+ var hdr = smbFill(fixed);
3967
+ smbAscii('NTLMSSP\0').copy(hdr, 0); hdr.writeUInt32LE(3, 8);
3968
+ ntlmField(lm.length, lmOff).copy(hdr, 12); ntlmField(nt.length, ntOff).copy(hdr, 20); ntlmField(dom.length, domOff).copy(hdr, 28);
3969
+ ntlmField(usr.length, userOff).copy(hdr, 36); ntlmField(ws.length, wsOff).copy(hdr, 44); ntlmField(0, cur).copy(hdr, 52);
3970
+ hdr.writeUInt32LE(NTLM_FLAGS, 60);
3971
+ var token = Buffer.concat([hdr, lm, nt, dom, usr, ws]);
3972
+ if (haveTs) { hmacMd5(sessionKey, Buffer.concat([ntlmNegotiate(), challenge, token])).copy(token, 72); } // (the MIC: over all three messages)
3973
+ return { token: token, sessionKey: sessionKey };
3974
+ }
3975
+ function ntlmAnonymous() {
3976
+ var ws = smbU16('STREMIOK'), fixed = 72, hdr = smbFill(fixed);
3977
+ smbAscii('NTLMSSP\0').copy(hdr, 0); hdr.writeUInt32LE(3, 8);
3978
+ ntlmField(1, fixed).copy(hdr, 12); ntlmField(0, fixed + 1).copy(hdr, 20); ntlmField(0, fixed + 1).copy(hdr, 28); ntlmField(0, fixed + 1).copy(hdr, 36);
3979
+ ntlmField(ws.length, fixed + 1).copy(hdr, 44); ntlmField(0, fixed + 1 + ws.length).copy(hdr, 52);
3980
+ hdr.writeUInt32LE((NTLM_FLAGS | NTLM_ANON) >>> 0, 60);
3981
+ return Buffer.concat([hdr, smbBytes([0]), ws]);
3982
+ }
3983
+ // One connection to one share (or IPC$, for the share list): requests matched to answers by their
3984
+ // message id, several at once (the player reads ahead).
3985
+ function SmbConn(o) {
3986
+ this.host = o.host; this.port = o.port || SMB_PORT; this.share = o.share; this.user = o.user || ''; this.pass = o.pass || ''; this.domain = o.domain || '';
3987
+ this.guest = !this.user;
3988
+ this.sock = null; this.rx = []; this.rxLen = 0; this.msgId = 0; this.sessionId = smbFill(8); this.treeId = 0;
3989
+ this.signKey = null; this.signing = false; this.pending = {}; this.dead = false; this.maxRead = 65536; this.last = Date.now(); this.users = 0;
3990
+ }
3991
+ SmbConn.prototype._take = function (chunk) {
3992
+ this.rx.push(chunk); this.rxLen += chunk.length;
3993
+ while (this.rxLen >= 4) {
3994
+ var head = this.rx.length === 1 ? this.rx[0] : Buffer.concat(this.rx, this.rxLen);
3995
+ this.rx = [head];
3996
+ var len = (head[1] << 16) | (head[2] << 8) | head[3];
3997
+ if (head[0] !== 0 || len > SMB_MSG_MAX) { this._die('a message that isn\'t SMB, or too large'); return; }
3998
+ if (head.length < 4 + len) { return; }
3999
+ var msg = head.slice(4, 4 + len), rest = head.slice(4 + len);
4000
+ this.rx = rest.length ? [rest] : []; this.rxLen = rest.length;
4001
+ this._dispatch(msg);
4002
+ if (this.dead) { return; }
4003
+ }
4004
+ };
4005
+ SmbConn.prototype._dispatch = function (msg) {
4006
+ if (msg.length < 64 || msg.readUInt32BE(0) !== 0xFE534D42) { return; } // (SMB 2 only)
4007
+ var status = msg.readUInt32LE(8) >>> 0, mid = smbR64(msg, 24);
4008
+ if (status === SMB_ST.PENDING) { return; } // (the answer follows)
4009
+ var p = this.pending[mid];
4010
+ if (!p) { return; }
4011
+ delete this.pending[mid];
4012
+ clearTimeout(p.timer);
4013
+ try { p.cb(status, msg.slice(0, 64), msg.slice(64)); } catch (e) { try { p.cb(-2, null, null); } catch (e2) {} } // (an answer too short for what it says: as an error)
4014
+ };
4015
+ SmbConn.prototype._die = function (why) {
4016
+ if (this.dead) { return; }
4017
+ this.dead = true;
4018
+ var p = this.pending; this.pending = {};
4019
+ Object.keys(p).forEach(function (k) { clearTimeout(p[k].timer); try { p[k].cb(-1, null, null); } catch (e) {} });
4020
+ try { if (this.sock) { this.sock.destroy(); } } catch (e) {}
4021
+ this.why = why;
4022
+ };
4023
+ SmbConn.prototype._send = function (command, body, charge, cb) {
4024
+ var self = this;
4025
+ if (this.dead) { cb(-1, null, null); return; }
4026
+ charge = charge || 1;
4027
+ var h = smbFill(64), id = this.msgId;
4028
+ this.msgId += charge; // (a request of several credits uses as many message ids)
4029
+ h.writeUInt32BE(0xFE534D42, 0); h.writeUInt16LE(64, 4); h.writeUInt16LE(charge, 6); h.writeUInt16LE(command, 12); h.writeUInt16LE(64, 14);
4030
+ smbW64(h, 24, id); h.writeUInt32LE(this.treeId >>> 0, 36); this.sessionId.copy(h, 40);
4031
+ if (this.signing && this.signKey && command !== SMB2.SESSION_SETUP) {
4032
+ h.writeUInt32LE(0x00000008, 16);
4033
+ crypto.createHmac('sha256', this.signKey).update(Buffer.concat([h, body])).digest().slice(0, 16).copy(h, 48);
4034
+ }
4035
+ var packet = Buffer.concat([h, body]), pfx = smbBytes([0, (packet.length >> 16) & 0xFF, (packet.length >> 8) & 0xFF, packet.length & 0xFF]);
4036
+ this.pending[id] = { cb: cb, timer: setTimeout(function () { if (self.pending[id]) { delete self.pending[id]; cb(-1, null, null); self._die('no answer in ' + (SMB_REQ_MS / 1000) + ' s'); } }, SMB_REQ_MS) };
4037
+ this.last = Date.now();
4038
+ try { this.sock.write(Buffer.concat([pfx, packet])); } catch (e) { this._die('write: ' + e.message); }
4039
+ };
4040
+ SmbConn.prototype.connect = function (done) {
4041
+ var self = this, finished = false;
4042
+ function finish(err) { if (finished) { return; } finished = true; clearTimeout(timer); if (err) { self._die(err.message); } done(err || null); }
4043
+ var timer = setTimeout(function () { var e = new Error('couldn\'t reach ' + self.host + ' (port ' + self.port + ')'); e.why = 'unreachable'; finish(e); }, SMB_CONNECT_MS);
4044
+ try { this.sock = net.connect(this.port, this.host); } catch (e) { var e0 = new Error('couldn\'t reach it: ' + e.message); e0.why = 'unreachable'; finish(e0); return; }
4045
+ this.sock.on('connect', function () {
4046
+ if (isSelfAddr(self.sock.remoteAddress)) { var es = new Error('not this TV'); es.why = 'unreachable'; finish(es); return; }
4047
+ self._negotiate(function (e1) {
4048
+ if (e1) { finish(e1); return; }
4049
+ self._session(function (e2) { if (e2) { finish(e2); return; } self._tree(finish); });
4050
+ });
4051
+ });
4052
+ this.sock.on('data', function (c) { self._take(c); });
4053
+ this.sock.on('error', function (e) { var er = new Error('couldn\'t reach it: ' + (e.code || e.message)); er.why = 'unreachable'; self._die(er.message); finish(er); });
4054
+ this.sock.on('close', function () { self._die('closed'); var ec = new Error('the server closed the connection'); ec.why = 'unreachable'; finish(ec); });
4055
+ try { this.sock.setNoDelay(true); } catch (e) {}
4056
+ };
4057
+ SmbConn.prototype._negotiate = function (cb) {
4058
+ var self = this, body = smbFill(40);
4059
+ body.writeUInt16LE(36, 0); body.writeUInt16LE(2, 2); body.writeUInt16LE(1, 4); body.writeUInt32LE(4, 8); // (2 dialects, signing on, large reads)
4060
+ crypto.randomBytes(16).copy(body, 12);
4061
+ body.writeUInt16LE(0x0202, 36); body.writeUInt16LE(0x0210, 38);
4062
+ this._send(SMB2.NEGOTIATE, body, 1, function (st, hdr, r) {
4063
+ if (st !== 0) { var e = st === -1 ? smbErr(-1) : new Error('it doesn\'t speak SMB 2 (only SMB 3, or SMB 1?)'); if (st !== -1) { e.why = 'smb3'; } cb(e); return; }
4064
+ if (r.length < 40) { cb(smbErr(-2, 'negotiate')); return; }
4065
+ self.dialect = r.readUInt16LE(4);
4066
+ if (self.dialect !== 0x0202 && self.dialect !== 0x0210) { var e2 = new Error('it doesn\'t speak SMB 2.0 or 2.1'); e2.why = 'smb3'; cb(e2); return; }
4067
+ self.signing = !!(r.readUInt16LE(2) & 2);
4068
+ self.maxRead = Math.max(65536, Math.min(r.readUInt32LE(32) || 65536, 8388608));
4069
+ cb(null);
4070
+ });
4071
+ };
4072
+ SmbConn.prototype._setup = function (token, cb) {
4073
+ var body = smbFill(24 + token.length);
4074
+ body.writeUInt16LE(25, 0); body.writeUInt8(this.signing ? 2 : 1, 3); body.writeUInt16LE(88, 12); body.writeUInt16LE(token.length, 14);
4075
+ token.copy(body, 24);
4076
+ this._send(SMB2.SESSION_SETUP, body, 1, cb);
4077
+ };
4078
+ SmbConn.prototype._session = function (done) {
4079
+ var self = this;
4080
+ this._setup(ntlmNegotiate(), function (st, hdr, r) {
4081
+ if (st !== SMB_ST.MORE_PROCESSING) { done(smbErr(st, 'sign-in')); return; }
4082
+ hdr.copy(self.sessionId, 0, 40, 48);
4083
+ var off = r.readUInt16LE(4) - 64, len = r.readUInt16LE(6);
4084
+ if (off < 0 || off + len > r.length) { done(smbErr(-2, 'sign-in')); return; }
4085
+ var t3;
4086
+ try {
4087
+ if (self.guest) { self.signing = false; t3 = { token: ntlmAnonymous() }; }
4088
+ else { t3 = ntlmAuthenticate(r.slice(off, off + len), self.user, self.pass, self.domain); self.signKey = t3.sessionKey; }
4089
+ } catch (e) { var er = new Error('sign-in: ' + e.message); er.why = 'other'; done(er); return; }
4090
+ self._setup(t3.token, function (st2, hdr2, r2) {
4091
+ if (st2 !== 0) { done(smbErr(st2, 'sign-in')); return; }
4092
+ var flags = r2.length >= 4 ? r2.readUInt16LE(2) : 0;
4093
+ if (!self.guest && !(flags & 3) && self.signKey) { self.signing = true; } // (SMB 2.1 on a real session: signed, as Samba expects)
4094
+ if (flags & 3) { self.signing = false; } // (a guest or null session: no key to sign with)
4095
+ done(null);
4096
+ });
4097
+ });
4098
+ };
4099
+ SmbConn.prototype._tree = function (done) {
4100
+ var self = this, unc = smbU16('\\\\' + this.host + '\\' + this.share), body = smbFill(8 + unc.length);
4101
+ body.writeUInt16LE(9, 0); body.writeUInt16LE(72, 4); body.writeUInt16LE(unc.length, 6); unc.copy(body, 8);
4102
+ this._send(SMB2.TREE_CONNECT, body, 1, function (st, hdr) {
4103
+ if (st !== 0) { done(smbErr(st, 'the share “' + self.share + '”')); return; }
4104
+ self.treeId = hdr.readUInt32LE(36);
4105
+ done(null);
4106
+ });
4107
+ };
4108
+ function smbPath(p) { return String(p || '').replace(/^[\\/]+|[\\/]+$/g, '').replace(/\//g, '\\'); }
4109
+ SmbConn.prototype.open = function (path, dir, cb, access) {
4110
+ var name = smbU16(smbPath(path)), body = smbFill(56 + Math.max(name.length, 1));
4111
+ body.writeUInt16LE(57, 0); body.writeUInt32LE(2, 4); body.writeUInt32LE(access || 0x00100081, 24); body.writeUInt32LE(7, 32); body.writeUInt32LE(1, 36);
4112
+ body.writeUInt32LE(dir ? 1 : 0x40, 40); body.writeUInt16LE(120, 44); body.writeUInt16LE(name.length, 46);
4113
+ name.copy(body, 56);
4114
+ this._send(SMB2.CREATE, body, 1, function (st, hdr, r) {
4115
+ if (st !== 0) { cb(smbErr(st)); return; }
4116
+ if (r.length < 80) { cb(smbErr(-2)); return; }
4117
+ cb(null, { id: r.slice(64, 80), size: smbR64(r, 48), dir: !!(r.readUInt32LE(56) & 0x10) });
4118
+ });
4119
+ };
4120
+ SmbConn.prototype.close = function (id) {
4121
+ var body = smbFill(24); body.writeUInt16LE(24, 0); id.copy(body, 8);
4122
+ this._send(SMB2.CLOSE, body, 1, function () {});
4123
+ };
4124
+ // A folder's entries: [{ name, dir, size }] (SMB_LIST_MAX at most, hidden "." and ".." left out).
4125
+ SmbConn.prototype.list = function (path, done) {
4126
+ var self = this;
4127
+ done = once(done);
4128
+ this.open(path, true, function (err, d) {
4129
+ if (err) { done(err); return; }
4130
+ var out = [], pat = smbU16('*'), rounds = 0;
4131
+ (function round(first) {
4132
+ var body = smbFill(32 + pat.length);
4133
+ body.writeUInt16LE(33, 0); body.writeUInt8(1, 2); body.writeUInt8(first ? 1 : 0, 3); d.id.copy(body, 8);
4134
+ body.writeUInt16LE(96, 24); body.writeUInt16LE(pat.length, 26); body.writeUInt32LE(65536, 28); pat.copy(body, 32);
4135
+ self._send(SMB2.QUERY_DIRECTORY, body, 1, function (st, hdr, r) {
4136
+ if (st === SMB_ST.NO_MORE_FILES || out.length >= SMB_LIST_MAX || rounds++ > 200) { self.close(d.id); done(null, out); return; }
4137
+ if (st !== 0) { self.close(d.id); done(smbErr(st)); return; }
4138
+ var off = r.readUInt16LE(2) - 64, len = r.readUInt32LE(4);
4139
+ if (off < 0 || off + len > r.length) { self.close(d.id); done(smbErr(-2)); return; }
4140
+ var b = r.slice(off, off + len), p = 0;
4141
+ for (var n = 0; p + 64 <= b.length && n < 4096; n++) {
4142
+ var next = b.readUInt32LE(p), nlen = b.readUInt32LE(p + 60), attrs = b.readUInt32LE(p + 56);
4143
+ if (p + 64 + nlen > b.length) { break; }
4144
+ var name = smbFromU16(b, p + 64, p + 64 + nlen), isDir = !!(attrs & 0x10);
4145
+ if (name !== '.' && name !== '..' && name && name.length <= 255 && !/[\0\/\\]/.test(name) && out.length < SMB_LIST_MAX) { out.push({ name: name, dir: isDir, size: isDir ? 0 : smbR64(b, p + 40) }); }
4146
+ if (!next) { break; }
4147
+ p += next;
4148
+ }
4149
+ round(false);
4150
+ });
4151
+ })(true);
4152
+ });
4153
+ };
4154
+ SmbConn.prototype.read = function (id, offset, length, cb) {
4155
+ var body = smbFill(49);
4156
+ body.writeUInt16LE(49, 0); body.writeUInt32LE(length, 4); smbW64(body, 8, offset); id.copy(body, 16);
4157
+ this._send(SMB2.READ, body, Math.max(1, Math.ceil(length / 65536)), function (st, hdr, r) {
4158
+ if (st === SMB_ST.END_OF_FILE) { cb(null, allocBuffer(0)); return; }
4159
+ if (st !== 0 && st !== SMB_ST.BUFFER_OVERFLOW) { cb(smbErr(st)); return; }
4160
+ var off = r.readUInt8(2) - 64, len = r.readUInt32LE(4);
4161
+ if (off < 0 || off + len > r.length || len > length) { cb(smbErr(-2)); return; }
4162
+ cb(null, r.slice(off, off + len), st === SMB_ST.BUFFER_OVERFLOW);
4163
+ });
4164
+ };
4165
+ // The share list (connected to IPC$): NetrShareEnum (MS-SRVS) over the \srvsvc pipe, DCE/RPC by
4166
+ // hand. Disk shares only; hidden and administrative ones (C$, ADMIN$, print$) left out.
4167
+ function rpcSyntax(uuid, major) {
4168
+ var h = uuid.replace(/-/g, ''), b = smbFill(20);
4169
+ b.writeUInt32LE(parseInt(h.slice(0, 8), 16), 0); b.writeUInt16LE(parseInt(h.slice(8, 12), 16), 4); b.writeUInt16LE(parseInt(h.slice(12, 16), 16), 6);
4170
+ for (var i = 0; i < 8; i++) { b[8 + i] = parseInt(h.slice(16 + i * 2, 18 + i * 2), 16); }
4171
+ b.writeUInt16LE(major, 16);
4172
+ return b;
4173
+ }
4174
+ function rpcPdu(type, callId, body) { var h = smbFill(16); h[0] = 5; h[2] = type; h[3] = 3; h[4] = 0x10; h.writeUInt16LE(16 + body.length, 8); h.writeUInt32LE(callId, 12); return Buffer.concat([h, body]); }
4175
+ function rpcU32s(list) { var b = smbFill(list.length * 4); list.forEach(function (v, i) { b.writeUInt32LE(v >>> 0, i * 4); }); return b; }
4176
+ function ndrStr(str) { var ch = smbU16(str + '\0'), n = ch.length / 2, pad = (4 - ch.length % 4) % 4, b = smbFill(12 + ch.length + pad); b.writeUInt32LE(n, 0); b.writeUInt32LE(n, 8); ch.copy(b, 12); return b; }
4177
+ SmbConn.prototype.pipe = function (id, input, cb) { // FSCTL_PIPE_TRANSCEIVE, then reads until the reply's last fragment
4178
+ var self = this, body = smbFill(56 + input.length), got = [], total = 0;
4179
+ body.writeUInt16LE(57, 0); body.writeUInt32LE(0x0011C017, 4); id.copy(body, 8); body.writeUInt32LE(120, 24); body.writeUInt32LE(input.length, 28);
4180
+ body.writeUInt32LE(8560, 44); body.writeUInt32LE(1, 48); input.copy(body, 56);
4181
+ function more(buf, overflow) {
4182
+ got.push(buf); total += buf.length;
4183
+ var all = Buffer.concat(got, total), p = 0, last = false;
4184
+ while (all.length - p >= 16) { var len = all.readUInt16LE(p + 8); if (len < 16 || all.length - p < len) { break; } if (all[p + 3] & 2) { last = true; } p += len; }
4185
+ if ((last && !overflow) || total > 1048576) { cb(null, all); return; }
4186
+ self.read(id, 0, 8560, function (e, chunk, ov) { if (e) { cb(e); return; } if (!chunk.length) { cb(null, all); return; } more(chunk, ov || chunk.length >= 8560); });
4187
+ }
4188
+ this._send(SMB2.IOCTL, body, 1, function (st, hdr, r) {
4189
+ if (st !== 0 && st !== SMB_ST.BUFFER_OVERFLOW) { cb(smbErr(st, 'the share list')); return; }
4190
+ var off = r.readUInt32LE(32) - 64, len = r.readUInt32LE(36);
4191
+ if (off < 0 || off + len > r.length) { cb(smbErr(-2, 'the share list')); return; }
4192
+ more(r.slice(off, off + len), st === SMB_ST.BUFFER_OVERFLOW);
4193
+ });
4194
+ };
4195
+ function rpcStub(all) { // the reply PDUs' stub data, joined; throws on a fault or a broken one
4196
+ var out = [], p = 0;
4197
+ while (all.length - p >= 24) {
4198
+ var len = all.readUInt16LE(p + 8), auth = all.readUInt16LE(p + 10);
4199
+ if (len < 24 || all.length - p < len) { break; }
4200
+ if (all[p + 2] === 3) { throw new Error('the server refused the call'); }
4201
+ if (all[p + 2] !== 2 || 24 > len - auth) { throw new Error('an answer it didn\'t expect'); }
4202
+ out.push(all.slice(p + 24, p + len - auth));
4203
+ p += len;
4204
+ }
4205
+ return Buffer.concat(out);
4206
+ }
4207
+ function parseShares(stub) {
4208
+ var p = 0;
4209
+ function u32() { if (p + 4 > stub.length) { throw new Error('cut short'); } var v = stub.readUInt32LE(p); p += 4; return v; }
4210
+ function str() { var max = u32(); u32(); var n = u32(); if (n > max || n > 1024 || p + n * 2 > stub.length) { throw new Error('a broken name'); } var s = smbFromU16(stub, p, p + n * 2).replace(/\0+$/, ''); p += n * 2; p += (4 - p % 4) % 4; return s; }
4211
+ u32(); u32();
4212
+ if (!u32()) { return []; }
4213
+ var count = u32();
4214
+ if (!u32() || !count) { return []; }
4215
+ if (u32() !== count || count > 1000) { throw new Error('a broken share list'); }
4216
+ var rows = [], i;
4217
+ for (i = 0; i < count; i++) { rows.push({ np: u32(), type: u32(), rp: u32() }); }
4218
+ for (i = 0; i < count; i++) { rows[i].name = rows[i].np ? str() : ''; rows[i].remark = rows[i].rp ? str() : ''; }
4219
+ return rows.filter(function (r) { return (r.type & 0x0FFFFFFF) === 0 && !(r.type & 0x80000000) && r.name && !/\$$/.test(r.name); })
4220
+ .map(function (r) { return { name: r.name.slice(0, 80), remark: r.remark.slice(0, 120) }; })
4221
+ .sort(function (a, b) { return a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1; });
4222
+ }
4223
+ SmbConn.prototype.shares = function (done) {
4224
+ var self = this;
4225
+ done = once(done);
4226
+ this.open('srvsvc', false, function (err, pipeId) {
4227
+ if (err) { done(err); return; }
4228
+ var id = pipeId.id;
4229
+ function fin(e, v) { self.close(id); done(e, v); }
4230
+ var bind = smbFill(56);
4231
+ bind.writeUInt16LE(4280, 0); bind.writeUInt16LE(4280, 2); bind[8] = 1; bind[14] = 1;
4232
+ rpcSyntax('4b324fc8-1670-01d3-1278-5a47bf6ee188', 3).copy(bind, 16); rpcSyntax('8a885d04-1ceb-11c9-9fe8-08002b104860', 2).copy(bind, 36);
4233
+ self.pipe(id, rpcPdu(11, 1, bind), function (e1, ack) {
4234
+ if (e1) { fin(e1); return; }
4235
+ if (ack.length < 16 || ack[2] !== 12) { var eb = new Error('the share list: the server refused'); eb.why = 'other'; fin(eb); return; }
4236
+ var stub = Buffer.concat([rpcU32s([0x00020000]), ndrStr('\\\\' + self.host), rpcU32s([1, 1, 0x00020004, 0, 0, 0xFFFFFFFF, 0x00020008, 0])]);
4237
+ var hdr = smbFill(8); hdr.writeUInt32LE(stub.length, 0); hdr.writeUInt16LE(15, 6);
4238
+ self.pipe(id, rpcPdu(0, 2, Buffer.concat([hdr, stub])), function (e2, reply) {
4239
+ if (e2) { fin(e2); return; }
4240
+ try {
4241
+ var s = rpcStub(reply), werr = s.length >= 4 ? s.readUInt32LE(s.length - 4) : 0;
4242
+ if (werr) { throw new Error('error 0x' + werr.toString(16)); }
4243
+ fin(null, parseShares(s));
4244
+ } catch (e3) { var er = new Error('the share list: ' + e3.message); er.why = 'other'; fin(er); }
4245
+ });
4246
+ });
4247
+ }, 0x0012019F);
4248
+ };
4249
+ // A share's folder from the app: smb://host[:port]/share/[path/] (a host in the home network), the
4250
+ // sign-in from X-Dav-Auth ("DOMAIN\user:password"; none: a guest), or null.
4251
+ function smbFolder(req, q, noShare) {
4252
+ var u = String(q.u || '').trim(), m = /^smb:\/\/([A-Za-z0-9._-]{1,253}|\[[0-9a-fA-F:.]{2,45}\])(?::(\d{1,5}))?\/([^\/\\?#]{0,80})(\/[^?#]*)?$/.exec(u);
4253
+ if (!m || u.length > 1000) { return null; }
4254
+ var host = m[1].replace(/^\[|\]$/g, ''), port = m[2] ? +m[2] : SMB_PORT, share = m[3];
4255
+ if (!isLanName(host) || isSelfAddr(host) || !(port > 0 && port < 65536) || (!share && !noShare)) { return null; }
4256
+ if (share && (share === '.' || share === '..' || /[\0"*:<>|]/.test(share))) { return null; }
4257
+ var base = String(m[4] || '/').replace(/^\/+|\/+$/g, '');
4258
+ if (base && base.split('/').some(function (s) { return !s || s === '.' || s === '..'; })) { return null; }
4259
+ var a = String((req.headers && req.headers['x-dav-auth']) || '');
4260
+ if (a && !/^[A-Za-z0-9+\/=]{4,1400}$/.test(a)) { return null; }
4261
+ var up = a ? fromBase64(a).toString('utf8') : '', colon = up.indexOf(':'), user = colon === -1 ? up : up.slice(0, colon), pass = colon === -1 ? '' : up.slice(colon + 1), domain = '';
4262
+ var dm = /^([^\\\/]{1,64})[\\\/](.+)$/.exec(user);
4263
+ if (dm) { domain = dm[1]; user = dm[2]; }
4264
+ return { host: host, port: port, share: share, base: base, user: user, pass: pass, domain: domain, auth: a };
4265
+ }
4266
+ // A path under the folder (its base, then rel), checked as davUrl does; null: not one.
4267
+ function smbRel(f, rel) {
4268
+ rel = String(rel == null ? '' : rel).replace(/^\/+|\/+$/g, '');
4269
+ if (rel.length > 1024 || rel.indexOf('\0') !== -1 || /\\/.test(rel)) { return null; }
4270
+ if (rel && rel.split('/').some(function (s) { return !s || s === '.' || s === '..'; })) { return null; }
4271
+ return [f.base, rel].filter(Boolean).join('/');
4272
+ }
4273
+ // Connections kept for reuse (by server, share and sign-in), SMB_CONN_MAX at most, closed unused.
4274
+ var _smbConns = {};
4275
+ function smbKey(f, share) { return f.host + '|' + f.port + '|' + share + '|' + crypto.createHash('sha256').update(f.domain + '\\' + f.user + ':' + f.pass).digest('hex'); }
4276
+ function smbConn(f, share, cb) {
4277
+ cb = once(cb);
4278
+ var k = smbKey(f, share), c = _smbConns[k];
4279
+ if (c && !c.dead) { c.last = Date.now(); cb(null, c); return; }
4280
+ if (c && c.waiting) { c.waiting.push(cb); return; }
4281
+ var keys = Object.keys(_smbConns);
4282
+ if (keys.length >= SMB_CONN_MAX) { keys.sort(function (a, b) { return _smbConns[a].last - _smbConns[b].last; }); _smbConns[keys[0]]._die('too many open'); delete _smbConns[keys[0]]; }
4283
+ c = new SmbConn({ host: f.host, port: f.port, share: share, user: f.user, pass: f.pass, domain: f.domain });
4284
+ c.waiting = [cb];
4285
+ _smbConns[k] = c;
4286
+ c.connect(function (err) {
4287
+ var w = c.waiting; c.waiting = null;
4288
+ if (err) { if (_smbConns[k] === c) { delete _smbConns[k]; } }
4289
+ w.forEach(function (fn) { fn(err, err ? null : c); });
4290
+ });
4291
+ }
4292
+ setInterval(function () {
4293
+ var now = Date.now();
4294
+ Object.keys(_smbConns).forEach(function (k) { var c = _smbConns[k]; if (c.dead || (!c.waiting && now - c.last > SMB_IDLE_MS && !Object.keys(c.pending).length && !c.users)) { c._die('unused'); delete _smbConns[k]; } });
4295
+ }, 30000);
4296
+ function smbList(f, rel, cb) {
4297
+ cb = once(cb);
4298
+ var p = smbRel(f, rel);
4299
+ if (p === null) { cb(upError('not a path in the share', 400)); return; }
4300
+ smbConn(f, f.share, function (err, c) {
4301
+ if (err) { cb(err); return; }
4302
+ c.list(p, function (e, entries) { if (e) { cb(e); return; } cb(null, { entries: entries }); });
4303
+ });
4304
+ }
4305
+ function smbWalk(f, st, cb) {
4306
+ cb = once(cb);
4307
+ var files = [], queue = [{ rel: '', depth: 0 }], active = 0, dirs = 0, truncated = false, started = Date.now();
4308
+ function end() { if (!active && !queue.length) { cb(null, { files: files, dirs: dirs, truncated: truncated }); } }
4309
+ function pump() {
4310
+ while (!st.cancelled && active < 2 && queue.length) {
4311
+ if (dirs >= SMB_WALK_DIRS || files.length >= SMB_WALK_FILES || Date.now() - started > SMB_WALK_MS) { truncated = true; queue = []; break; }
4312
+ var d = queue.shift();
4313
+ dirs++; active++;
4314
+ (function (d) {
4315
+ smbList(f, d.rel, function (err, r) {
4316
+ active--;
4317
+ if (st.cancelled) { return; }
4318
+ if (err) { if (!d.rel) { st.cancelled = true; cb(err); return; } truncated = true; }
4319
+ else {
4320
+ var names = r.entries.map(function (e) { return e.name; });
4321
+ r.entries.forEach(function (e) {
4322
+ if (HIDDEN_NAME.test(e.name)) { return; }
4323
+ var p = d.rel ? d.rel + '/' + e.name : e.name;
4324
+ if (e.dir) { if (d.depth < SMB_WALK_DEPTH) { queue.push({ rel: p, depth: d.depth + 1 }); } else { truncated = true; } }
4325
+ else if (walkWants(e.name, names) && files.length < SMB_WALK_FILES) { files.push({ p: p, size: e.size }); }
4326
+ });
4327
+ }
4328
+ pump();
4329
+ });
4330
+ })(d);
4331
+ }
4332
+ end();
4333
+ }
4334
+ pump();
4335
+ }
4336
+ // readAt over a file of the share (mediaInfo, subtitles): its size from the open; done() closes it.
4337
+ function smbOpenFile(f, rel, cb) {
4338
+ var p = smbRel(f, rel);
4339
+ if (p === null || !rel) { cb(upError('not a path in the share', 400)); return; }
4340
+ smbConn(f, f.share, function (err, c) {
4341
+ if (err) { cb(err); return; }
4342
+ c.open(p, false, function (e, h) {
4343
+ if (e) { cb(e); return; }
4344
+ c.users++;
4345
+ var closed = false;
4346
+ cb(null, function readAt(off, len, rcb) {
4347
+ var want = Math.max(0, Math.min(len, h.size - off)), parts = [], got = 0;
4348
+ (function next() {
4349
+ if (got >= want) { rcb(null, Buffer.concat(parts, got), h.size); return; }
4350
+ c.read(h.id, off + got, Math.min(SMB_READ, c.maxRead, want - got), function (re, data) {
4351
+ if (re) { rcb(re); return; }
4352
+ if (!data.length) { rcb(null, Buffer.concat(parts, got), h.size); return; }
4353
+ parts.push(data); got += data.length; next();
4354
+ });
4355
+ })();
4356
+ }, function done() { if (!closed) { closed = true; c.users--; c.close(h.id); } }, h.size);
4357
+ });
4358
+ });
4359
+ }
4360
+ function smbSub(f, rel, cb) {
4361
+ cb = once(cb);
4362
+ if (!SUB_EXT.test(String(rel))) { cb(upError('not a subtitle file in the share', 400)); return; }
4363
+ smbOpenFile(f, rel, function (err, readAt, done, size) {
4364
+ if (err) { cb(err); return; }
4365
+ if (size > SMB_SUB_MAX) { done(); cb(upError('too large for a subtitle file', 413)); return; }
4366
+ readAt(0, size, function (e, buf) { done(); if (e) { cb(e); return; } cb(null, decodeText(buf)); });
4367
+ });
4368
+ }
4369
+ // A file of the share for the player: its byte range (Range) read and sent on, the server's
4370
+ // largest read at a time, as fast as the player takes it.
4371
+ function smbFileRelay(f, rel, req, res) {
4372
+ var gone = false;
4373
+ res.on('close', function () { gone = true; });
4374
+ smbOpenFile(f, rel, function (err, readAt, done, size) {
4375
+ if (err) { if (!gone) { send(res, err.status === 400 || err.status === 404 ? err.status : 502, 'text/plain', 'failed: ' + (err.message || 'unknown')); } return; }
4376
+ if (gone) { done(); return; }
4377
+ var start = 0, end = size - 1, partial = false, m = /^bytes=(\d*)-(\d*)$/.exec(String(req.headers.range || ''));
4378
+ if (m && (m[1] !== '' || m[2] !== '')) {
4379
+ partial = true;
4380
+ if (m[1] === '') { start = Math.max(0, size - (+m[2])); } else { start = +m[1]; if (m[2] !== '') { end = Math.min(+m[2], size - 1); } }
4381
+ }
4382
+ if (start > end || start >= size) { done(); res.writeHead(416, { 'Content-Range': 'bytes */' + size, 'Cache-Control': 'no-store' }); res.end(); return; }
4383
+ var h = { 'Content-Type': 'application/octet-stream', 'Content-Length': String(end - start + 1), 'Accept-Ranges': 'bytes', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' };
4384
+ if (partial) { h['Content-Range'] = 'bytes ' + start + '-' + end + '/' + size; }
4385
+ res.writeHead(partial ? 206 : 200, h);
4386
+ var pos = start;
4387
+ (function pump() {
4388
+ if (gone || pos > end) { done(); if (!gone) { try { res.end(); } catch (e) {} } return; }
4389
+ readAt(pos, Math.min(SMB_READ, end - pos + 1), function (re, data) {
4390
+ if (gone) { done(); return; }
4391
+ if (re || !data.length) { done(); try { res.destroy(); } catch (e) {} return; } // (cut short: the connection dropped, so the player knows; ended, it would wait for the rest)
4392
+ pos += data.length;
4393
+ if (res.write(data)) { pump(); } else { res.once('drain', pump); }
4394
+ });
4395
+ })();
4396
+ });
4397
+ }
4398
+ function smbProblem(err) { return { why: err.why || 'other', message: String(err.message || 'unknown').slice(0, 300) }; }
4399
+ function smbControl(req, res, path, query, leaving) {
4400
+ if (!entryAllowed(req, query)) { send(res, 403, 'text/plain', 'not allowed (token)'); return; }
4401
+ var q = davQ(query), f = smbFolder(req, q, path === '/smb/shares');
4402
+ if (!f) { send(res, 400, 'text/plain', 'not a share in the home network'); return; }
4403
+ function answer(err, r) {
4404
+ if (!err) { send(res, 200, 'application/json', JSON.stringify(r)); return; }
4405
+ if (err.status === 400) { send(res, 400, 'text/plain', err.message); return; }
4406
+ send(res, 200, 'application/json', JSON.stringify(smbProblem(err)));
4407
+ }
4408
+ if (path === '/smb/shares') {
4409
+ var c = new SmbConn({ host: f.host, port: f.port, share: 'IPC$', user: f.user, pass: f.pass, domain: f.domain });
4410
+ leaving.push(function () { c._die('left'); });
4411
+ c.connect(function (err) {
4412
+ if (err) { answer(err); return; }
4413
+ c.shares(function (e, shares) { c._die('done'); if (e) { answer(e); return; } answer(null, { shares: shares }); });
4414
+ });
4415
+ return;
4416
+ }
4417
+ if (path === '/smb/list') { smbList(f, q.p, answer); return; }
4418
+ if (path === '/smb/walk') {
4419
+ var st = { cancelled: false };
4420
+ leaving.push(function () { st.cancelled = true; });
4421
+ smbWalk(f, st, answer);
4422
+ return;
4423
+ }
4424
+ if (path === '/smb/sub') {
4425
+ smbSub(f, q.p, function (err, text) {
4426
+ if (err) { send(res, err.status === 400 ? 400 : err.status === 413 ? 413 : 502, 'text/plain', 'failed: ' + (err.message || 'unknown')); return; }
4427
+ send(res, 200, 'text/plain; charset=utf-8', text);
4428
+ });
4429
+ return;
4430
+ }
4431
+ if (path === '/smb/mi') {
4432
+ if (!VIDEO_EXT.test(String(q.p || ''))) { send(res, 400, 'text/plain', 'not a video in the share'); return; }
4433
+ smbOpenFile(f, q.p, function (err, readAt, done) {
4434
+ if (err) { send(res, 502, 'text/plain', 'failed: ' + (err.message || 'unknown')); return; }
4435
+ var stop = mediaInfo(readAt, function (e, r) {
4436
+ done();
4437
+ if (e) { send(res, e.status && e.status < 600 ? e.status : 502, 'text/plain', 'failed: ' + (e.message || 'unknown')); return; }
4438
+ send(res, 200, 'application/json', JSON.stringify(r));
4439
+ });
4440
+ if (stop) { leaving.push(stop); }
4441
+ });
4442
+ return;
4443
+ }
4444
+ if (path === '/smb/open') { send(res, 200, 'application/json', JSON.stringify({ ticket: netTicket('smb', f) })); return; }
4445
+ send(res, 404, 'text/plain', 'not found');
4446
+ }
4447
+
4448
+ // ---- DLNA media servers: /dlna/discover, /dlna/list, /dlna/walk, /dlna/sub, /dlna/mi, /dlna/open ----
4449
+ // A NAS's or a computer's media server (miniDLNA, Serviio, Windows' media sharing, a router's) as
4450
+ // a network folder: found on the home network when asked (SSDP: multicast and broadcast, for
4451
+ // DLNA_SEARCH_MS), listed to add (none added on its own), its folders browsed (ContentDirectory
4452
+ // Browse over SOAP), its videos played from its own links. A server knows its folders by id, not by
4453
+ // path: their names are kept here per server (DLNA_SERVERS of them, DLNA_ITEMS names each, in
4454
+ // memory), so a path in it ("Films/Dune.mkv") finds its id again; a video's title without an
4455
+ // extension gets one from its type (the name matching needs one). Only servers in the home network;
4456
+ // no sign-in (DLNA has none). Adapted from Tessel's (MIT License, Copyright (c) 2026 Patrick:
4457
+ // github.com/PatrickSt1991/tessel-tizen-tv, tizen-app/service/service.js).
4458
+ var DLNA_SEARCH_MS = 3000, DLNA_HTTP_MS = 8000, DLNA_MAX_BYTES = 8 * 1048576, DLNA_PAGE = 200, DLNA_ENTRIES = 3000, DLNA_SERVERS = 8, DLNA_ITEMS = 40000, DLNA_FOUND_MAX = 32;
4459
+ var DLNA_WALK_DIRS = 2000, DLNA_WALK_FILES = 20000, DLNA_WALK_DEPTH = 12, DLNA_WALK_MS = 90000;
4460
+ var DLNA_MIME_EXT = { 'video/x-matroska': 'mkv', 'video/mp4': 'mp4', 'video/x-m4v': 'm4v', 'video/x-msvideo': 'avi', 'video/avi': 'avi', 'video/mpeg': 'mpg', 'video/mp2t': 'ts', 'video/vnd.dlna.mpeg-tts': 'ts',
4461
+ 'video/quicktime': 'mov', 'video/webm': 'webm', 'video/x-ms-wmv': 'wmv', 'video/x-flv': 'flv', 'video/3gpp': '3gp', 'video/ogg': 'ogv' };
4462
+ function dlnaTag(xml, name) { // the first <name> (any prefix): its text, unescaped
4463
+ var m = new RegExp('<(?:[\\w.-]+:)?' + name + '(?:\\s[^>]*)?>([\\s\\S]*?)</(?:[\\w.-]+:)?' + name + '\\s*>', 'i').exec(xml || '');
4464
+ return m ? xmlText(m[1]).trim() : '';
4465
+ }
4466
+ function dlnaEach(xml, name, max) { // every <name …>…</name> or <name …/>: [{ attrs, body }]
4467
+ var out = [], m, re = new RegExp('<(?:[\\w.-]+:)?' + name + '\\b([^>]*?)(?:/>|>([\\s\\S]*?)</(?:[\\w.-]+:)?' + name + '\\s*>)', 'gi');
4468
+ while ((m = re.exec(xml || '')) && out.length < (max || 10000)) { out.push({ attrs: m[1] || '', body: m[2] || '' }); }
4469
+ return out;
4470
+ }
4471
+ function dlnaAttr(attrs, name) {
4472
+ var m = new RegExp('(?:^|\\s)' + name.replace(/[.*+?^${}()|[\]\\:\/-]/g, '\\$&') + '\\s*=\\s*(?:"([^"]*)"|\'([^\']*)\')', 'i').exec(attrs || '');
4473
+ return m ? xmlText(m[1] !== undefined ? m[1] : m[2]) : '';
4474
+ }
4475
+ // A link the server may give: http(s), in the home network, not the TV itself.
4476
+ function dlnaLanUrl(u) {
4477
+ var pu;
4478
+ try { pu = urllib.parse(String(u || '')); } catch (e) { return null; }
4479
+ if ((pu.protocol !== 'http:' && pu.protocol !== 'https:') || !pu.hostname || !isLanName(pu.hostname) || isSelfAddr(pu.hostname)) { return null; }
4480
+ return pu;
4481
+ }
4482
+ // One request to a server (description, Browse): cb(err, status, text), DLNA_MAX_BYTES, DLNA_HTTP_MS.
4483
+ function dlnaHttp(target, method, headers, body, cb) {
4484
+ cb = once(cb);
4485
+ var pu = dlnaLanUrl(target), r = null;
4486
+ if (!pu) { cb(upError('not a server in the home network', 400)); return noop; }
4487
+ var timer = setTimeout(function () { try { if (r) { r.abort(); } } catch (e) {} cb(upError('no answer in ' + (DLNA_HTTP_MS / 1000) + ' s', 504)); }, DLNA_HTTP_MS);
4488
+ try {
4489
+ var data = body ? toBuffer(body) : null, h = { 'User-Agent': 'StremioK' };
4490
+ Object.keys(headers || {}).forEach(function (k) { h[k] = headers[k]; });
4491
+ if (data) { h['Content-Length'] = data.length; }
4492
+ r = (pu.protocol === 'https:' ? https : http).request({ hostname: pu.hostname, port: pu.port, path: pu.path, method: method, headers: h, agent: false }, function (resp) {
4493
+ var chunks = [], size = 0;
4494
+ resp.on('data', function (c) { size += c.length; if (size > DLNA_MAX_BYTES) { clearTimeout(timer); try { r.abort(); } catch (e) {} cb(upError('its answer is too large', 502)); return; } chunks.push(c); });
4495
+ resp.on('end', function () { clearTimeout(timer); cb(null, resp.statusCode, Buffer.concat(chunks, size).toString('utf8')); });
4496
+ resp.on('error', function (e) { clearTimeout(timer); cb(e); });
4497
+ });
4498
+ guardSelf(r, function () { clearTimeout(timer); cb(upError('not a server in the home network', 400)); });
4499
+ r.on('error', function (e) { clearTimeout(timer); cb(e); });
4500
+ if (data) { r.write(data); }
4501
+ r.end();
4502
+ } catch (e) { clearTimeout(timer); cb(e); }
4503
+ return function () { clearTimeout(timer); try { if (r) { r.abort(); } } catch (e) {} };
4504
+ }
4505
+ // A device description: { id, name, control } of its ContentDirectory, or null (not a media server).
4506
+ function dlnaDescription(xml, location) {
4507
+ var services = dlnaEach(xml, 'service', 50), control = '';
4508
+ for (var i = 0; i < services.length && !control; i++) { if (/:ContentDirectory:/i.test(dlnaTag(services[i].body, 'serviceType'))) { control = dlnaTag(services[i].body, 'controlURL'); } }
4509
+ if (!control) { return null; }
4510
+ var abs;
4511
+ try { abs = urllib.resolve(dlnaTag(xml, 'URLBase') || location, control); } catch (e) { return null; }
4512
+ var pu = dlnaLanUrl(abs);
4513
+ if (!pu) { return null; }
4514
+ return { id: (dlnaTag(xml, 'UDN') || location).slice(0, 120), name: (dlnaTag(xml, 'friendlyName') || pu.hostname).slice(0, 80), control: abs };
4515
+ }
4516
+ function dlnaBrowseBody(id, start) {
4517
+ return '<?xml version="1.0" encoding="utf-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
4518
+ '<s:Body><u:Browse xmlns:u="urn:schemas-upnp-org:service:ContentDirectory:1"><ObjectID>' + String(id).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;') +
4519
+ '</ObjectID><BrowseFlag>BrowseDirectChildren</BrowseFlag><Filter>*</Filter><StartingIndex>' + start + '</StartingIndex><RequestedCount>' + DLNA_PAGE +
4520
+ '</RequestedCount><SortCriteria></SortCriteria></u:Browse></s:Body></s:Envelope>';
4521
+ }
4522
+ // A Browse page's DIDL-Lite: folders, and videos with their link, size and subtitle files.
4523
+ function dlnaDidl(didl) {
4524
+ var out = [];
4525
+ dlnaEach(didl, 'container', DLNA_ENTRIES).forEach(function (c) { out.push({ id: dlnaAttr(c.attrs, 'id'), title: dlnaTag(c.body, 'title'), dir: true }); });
4526
+ dlnaEach(didl, 'item', DLNA_ENTRIES).forEach(function (it) {
4527
+ if (!/videoItem/i.test(dlnaTag(it.body, 'class'))) { return; } // (videos only: Local plays nothing else)
4528
+ var res = dlnaEach(it.body, 'res', 20), pick = null, subs = [];
4529
+ res.forEach(function (r) {
4530
+ var url = xmlText(r.body).trim(), mime = (String(dlnaAttr(r.attrs, 'protocolInfo')).split(':')[2] || '').toLowerCase();
4531
+ if (!/^https?:\/\//i.test(url)) { return; }
4532
+ if (/^text\/|subrip|x-ssa|x-ass|smi/.test(mime)) { subs.push(url); return; }
4533
+ if (!pick && /^http-get:/i.test(dlnaAttr(r.attrs, 'protocolInfo') || 'http-get:')) { pick = { url: url, mime: mime, size: +dlnaAttr(r.attrs, 'size') || 0 }; }
4534
+ });
4535
+ ['CaptionInfoEx', 'CaptionInfo'].forEach(function (t) { dlnaEach(it.body, t, 10).forEach(function (cp) { var u = xmlText(cp.body).trim(); if (/^https?:\/\//i.test(u)) { subs.push(u); } }); });
4536
+ if (pick) { out.push({ id: dlnaAttr(it.attrs, 'id'), title: dlnaTag(it.body, 'title'), dir: false, url: pick.url, mime: pick.mime, size: pick.size, subs: subs.slice(0, 8) }); }
4537
+ });
4538
+ return out;
4539
+ }
4540
+ // The servers' names kept here: per control URL, a path's id (folders) or its link (files).
4541
+ var _dlna = {};
4542
+ function dlnaServer(control) {
4543
+ var key = 'c:' + control, s = _dlna[key]; // (prefixed: no address can name an object's own properties)
4544
+ if (!s) {
4545
+ var keys = Object.keys(_dlna);
4546
+ if (keys.length >= DLNA_SERVERS) { keys.sort(function (a, b) { return _dlna[a].at - _dlna[b].at; }); delete _dlna[keys[0]]; }
4547
+ s = _dlna[key] = { dirs: { '': '0' }, files: {}, n: 0, at: Date.now() };
4548
+ }
4549
+ s.at = Date.now();
4550
+ return s;
4551
+ }
4552
+ function dlnaName(title) { return String(title || '?').replace(/[\/\\\0]/g, '-').replace(/^\.+/, '').trim().slice(0, 200) || '?'; }
4553
+ function dlnaExt(e) {
4554
+ var path = '';
4555
+ try { path = String(urllib.parse(e.url).pathname || ''); } catch (x) {}
4556
+ var m = /\.([a-z0-9]{2,4})$/i.exec(path), ext = m && VIDEO_EXT.test('.' + m[1]) ? m[1].toLowerCase() : '';
4557
+ return ext || DLNA_MIME_EXT[e.mime] || 'mkv';
4558
+ }
4559
+ function dlnaSubExt(u) { var m = /\.(srt|vtt|ass|ssa|smi)(?:[?#]|$)/i.exec(String(u || '')); return m ? m[1].toLowerCase() : 'srt'; }
4560
+ // A folder's entries (its id), page by page, named and kept: cb(err, [{ name, dir, size }]).
4561
+ function dlnaFolder(control, rel, id, cb) {
4562
+ cb = once(cb);
4563
+ var s = dlnaServer(control), raw = [];
4564
+ (function page(start) {
4565
+ dlnaHttp(control, 'POST', { 'Content-Type': 'text/xml; charset="utf-8"', 'SOAPACTION': '"urn:schemas-upnp-org:service:ContentDirectory:1#Browse"' }, dlnaBrowseBody(id, start), function (err, status, xml) {
4566
+ if (err) { cb(err); return; }
4567
+ if (status !== 200) { var e = upError('the server refused (' + (dlnaTag(xml, 'errorDescription') || 'HTTP ' + status) + ')', 502); e.why = 'missing'; cb(e); return; }
4568
+ var got = dlnaDidl(dlnaTag(xml, 'Result')), returned = +dlnaTag(xml, 'NumberReturned') || 0, total = +dlnaTag(xml, 'TotalMatches') || 0;
4569
+ raw = raw.concat(got);
4570
+ if (returned > 0 && start + returned < total && raw.length < DLNA_ENTRIES) { page(start + returned); return; }
4571
+ var out = [], seen = {};
4572
+ function unique(n) { var base = n, i = 2, dot = n.lastIndexOf('.'); while (seen[n.toLowerCase()]) { n = dot > 0 ? base.slice(0, dot) + ' (' + (i++) + ')' + base.slice(dot) : base + ' (' + (i++) + ')'; } seen[n.toLowerCase()] = 1; return n; }
4573
+ raw.slice(0, DLNA_ENTRIES).forEach(function (e) {
4574
+ var name = dlnaName(e.title), p;
4575
+ if (e.dir) { name = unique(name); p = rel ? rel + '/' + name : name; if (s.n < DLNA_ITEMS) { s.dirs[p] = e.id; s.n++; } out.push({ name: name, dir: true, size: 0 }); return; }
4576
+ if (!VIDEO_EXT.test(name)) { name += '.' + dlnaExt(e); }
4577
+ name = unique(name);
4578
+ p = rel ? rel + '/' + name : name;
4579
+ if (s.n < DLNA_ITEMS) { s.files[p] = e.url; s.n++; }
4580
+ out.push({ name: name, dir: false, size: e.size });
4581
+ e.subs.forEach(function (su, k) { // (its subtitle files, as files beside it: Film.srt, Film.2.srt…)
4582
+ var sn = unique(name.replace(/\.[^.]+$/, '') + (k ? '.' + (k + 1) : '') + '.' + dlnaSubExt(su)), sp = rel ? rel + '/' + sn : sn;
4583
+ if (s.n < DLNA_ITEMS) { s.files[sp] = su; s.n++; }
4584
+ out.push({ name: sn, dir: false, size: 0 });
4585
+ });
4586
+ });
4587
+ cb(null, out);
4588
+ });
4589
+ })(0);
4590
+ }
4591
+ // A path's folder id, its parents browsed for their names when not known yet: cb(err, id).
4592
+ function dlnaDirId(control, rel, cb) {
4593
+ var s = dlnaServer(control);
4594
+ if (Object.prototype.hasOwnProperty.call(s.dirs, rel)) { cb(null, s.dirs[rel]); return; }
4595
+ var segs = rel.split('/'), parent = segs.slice(0, -1).join('/');
4596
+ dlnaDirId(control, parent, function (err, pid) {
4597
+ if (err) { cb(err); return; }
4598
+ dlnaFolder(control, parent, pid, function (e2) {
4599
+ if (e2) { cb(e2); return; }
4600
+ if (Object.prototype.hasOwnProperty.call(s.dirs, rel)) { cb(null, s.dirs[rel]); return; }
4601
+ var e = upError('no such folder there', 404); e.why = 'missing'; cb(e);
4602
+ });
4603
+ });
4604
+ }
4605
+ // A file's link (video or subtitle file), its folder browsed when not known yet.
4606
+ function dlnaFileUrl(control, rel, cb) {
4607
+ var s = dlnaServer(control);
4608
+ if (Object.prototype.hasOwnProperty.call(s.files, rel)) { cb(null, s.files[rel]); return; }
4609
+ var parent = rel.split('/').slice(0, -1).join('/');
4610
+ dlnaDirId(control, parent, function (err, pid) {
4611
+ if (err) { cb(err); return; }
4612
+ dlnaFolder(control, parent, pid, function (e2) {
4613
+ if (e2) { cb(e2); return; }
4614
+ if (Object.prototype.hasOwnProperty.call(s.files, rel)) { cb(null, s.files[rel]); return; }
4615
+ var e = upError('no such file there', 404); e.why = 'missing'; cb(e);
4616
+ });
4617
+ });
4618
+ }
4619
+ // A server from the app: its control URL (?u=dlna:<control>), in the home network, or null.
4620
+ function dlnaOf(q) {
4621
+ var u = String(q.u || '');
4622
+ if (u.indexOf('dlna:') !== 0 || u.length > 1100) { return null; }
4623
+ var control = u.slice(5).replace(/\/+$/, '').replace(/#$/, '');
4624
+ return dlnaLanUrl(control) ? { control: control } : null;
4625
+ }
4626
+ function dlnaRel(rel) {
4627
+ rel = String(rel == null ? '' : rel).replace(/^\/+|\/+$/g, '');
4628
+ if (rel.length > 1024 || rel.indexOf('\0') !== -1 || (rel && rel.split('/').some(function (s) { return !s || s === '.' || s === '..'; }))) { return null; }
4629
+ return rel;
4630
+ }
4631
+ // The media servers on the home network, asked for now: cb([{ id, name, control }]).
4632
+ function dlnaDiscover(cb) {
4633
+ cb = once(cb);
4634
+ var dgram = null, locations = [], sockets = [], done = false;
4635
+ try { dgram = require('dgram'); } catch (e) { cb([]); return; }
4636
+ var msgs = ['urn:schemas-upnp-org:device:MediaServer:1', 'urn:schemas-upnp-org:service:ContentDirectory:1'].map(function (st) {
4637
+ return toBuffer('M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: "ssdp:discover"\r\nMX: 2\r\nST: ' + st + '\r\n\r\n');
3267
4638
  });
4639
+ var ifaces = [];
4640
+ try {
4641
+ var nets = require('os').networkInterfaces();
4642
+ Object.keys(nets).forEach(function (n) { (nets[n] || []).forEach(function (a) { if (a && (a.family === 'IPv4' || a.family === 4) && !a.internal && a.address) { ifaces.push(a); } }); });
4643
+ } catch (e) {}
4644
+ function bcast(a) { // an interface's broadcast address
4645
+ var ip = a.address.split('.').map(Number), m = String(a.netmask || '255.255.255.0').split('.').map(Number);
4646
+ return ip.length === 4 && m.length === 4 ? ip.map(function (x, i) { return (x | (~m[i] & 255)) & 255; }).join('.') : '';
4647
+ }
4648
+ function onMsg(msg, rinfo) {
4649
+ var t = String(msg).split(/\r?\n/), h = {};
4650
+ if (!/^HTTP\/1\.[01] 200|^NOTIFY /i.test(t[0] || '')) { return; }
4651
+ t.slice(1).forEach(function (l) { var i = l.indexOf(':'); if (i > 0) { h[l.slice(0, i).trim().toLowerCase()] = l.slice(i + 1).trim(); } });
4652
+ if (h.location && dlnaLanUrl(h.location) && locations.indexOf(h.location) === -1 && locations.length < DLNA_FOUND_MAX && rinfo && isLanName(rinfo.address)) { locations.push(h.location); }
4653
+ }
4654
+ function open(a) {
4655
+ var sock;
4656
+ try { sock = dgram.createSocket('udp4'); } catch (e) { return; }
4657
+ sockets.push(sock);
4658
+ sock.on('message', onMsg);
4659
+ sock.on('error', function () { try { sock.close(); } catch (e) {} });
4660
+ function ask() {
4661
+ msgs.forEach(function (m) {
4662
+ var to = ['239.255.255.250'].concat(a ? [bcast(a), '255.255.255.255'].filter(Boolean) : []);
4663
+ to.forEach(function (addr) { try { sock.send(m, 0, m.length, 1900, addr, function () {}); } catch (e) {} });
4664
+ });
4665
+ }
4666
+ function ready() { if (a) { try { sock.setBroadcast(true); } catch (e) {} } ask(); setTimeout(function () { if (!done) { ask(); } }, 800); } // (UDP gets lost: asked twice)
4667
+ try { if (a) { sock.bind(0, a.address, ready); } else { sock.bind(ready); } } catch (e) {}
4668
+ }
4669
+ open(null);
4670
+ ifaces.forEach(open);
4671
+ setTimeout(function () {
4672
+ done = true;
4673
+ sockets.forEach(function (s) { try { s.close(); } catch (e) {} });
4674
+ var found = [], left = locations.length;
4675
+ if (!left) { cb([]); return; }
4676
+ locations.forEach(function (loc) {
4677
+ dlnaHttp(loc, 'GET', null, null, function (err, status, xml) {
4678
+ var d = !err && status === 200 ? dlnaDescription(xml, loc) : null;
4679
+ if (d && !found.some(function (x) { return x.id === d.id; })) { found.push(d); }
4680
+ if (--left === 0) { cb(found.sort(function (x, y) { return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1; })); }
4681
+ });
4682
+ });
4683
+ }, DLNA_SEARCH_MS);
4684
+ }
4685
+ function dlnaWalk(control, st, cb) {
4686
+ cb = once(cb);
4687
+ var files = [], queue = [{ rel: '', depth: 0 }], active = 0, dirs = 0, truncated = false, started = Date.now();
4688
+ function end() { if (!active && !queue.length) { cb(null, { files: files, dirs: dirs, truncated: truncated }); } }
4689
+ function pump() {
4690
+ while (!st.cancelled && active < 2 && queue.length) {
4691
+ if (dirs >= DLNA_WALK_DIRS || files.length >= DLNA_WALK_FILES || Date.now() - started > DLNA_WALK_MS) { truncated = true; queue = []; break; }
4692
+ var d = queue.shift();
4693
+ dirs++; active++;
4694
+ (function (d) {
4695
+ dlnaDirId(control, d.rel, function (err, id) {
4696
+ if (err) { active--; if (!d.rel) { st.cancelled = true; cb(err); return; } truncated = true; pump(); return; }
4697
+ dlnaFolder(control, d.rel, id, function (e2, entries) {
4698
+ active--;
4699
+ if (st.cancelled) { return; }
4700
+ if (e2) { if (!d.rel) { st.cancelled = true; cb(e2); return; } truncated = true; }
4701
+ else {
4702
+ entries.forEach(function (e) {
4703
+ var p = d.rel ? d.rel + '/' + e.name : e.name;
4704
+ if (e.dir) { if (d.depth < DLNA_WALK_DEPTH) { queue.push({ rel: p, depth: d.depth + 1 }); } else { truncated = true; } }
4705
+ else if ((VIDEO_EXT.test(e.name) || SUB_EXT.test(e.name)) && files.length < DLNA_WALK_FILES) { files.push({ p: p, size: e.size || 0 }); }
4706
+ });
4707
+ }
4708
+ pump();
4709
+ });
4710
+ });
4711
+ })(d);
4712
+ }
4713
+ end();
4714
+ }
4715
+ pump();
4716
+ }
4717
+ // A server's file for the player: sent on to its own link (the same server's, in the home network).
4718
+ function dlnaFileRedirect(f, rel, res) {
4719
+ dlnaFileUrl(f.control, rel, function (err, url) {
4720
+ if (err) { send(res, err.status || 502, 'text/plain', 'failed: ' + (err.message || 'unknown')); return; }
4721
+ var to = dlnaLanUrl(url), from = dlnaLanUrl(f.control);
4722
+ if (!to || !from || to.hostname !== from.hostname) { send(res, 403, 'text/plain', 'a link off the server'); return; }
4723
+ res.writeHead(302, { Location: url, 'Cache-Control': 'no-store' });
4724
+ res.end();
4725
+ });
4726
+ }
4727
+ function dlnaControl(req, res, path, query, leaving) {
4728
+ if (!entryAllowed(req, query)) { send(res, 403, 'text/plain', 'not allowed (token)'); return; }
4729
+ function answer(err, r) {
4730
+ if (!err) { send(res, 200, 'application/json', JSON.stringify(r)); return; }
4731
+ if (err.status === 400) { send(res, 400, 'text/plain', err.message); return; }
4732
+ send(res, 200, 'application/json', JSON.stringify({ why: err.why || (/no answer|ECONN|EHOST|ENET/.test(String(err.message || err.code)) ? 'unreachable' : 'other'), message: String(err.message || err.code || 'unknown').slice(0, 300) }));
4733
+ }
4734
+ if (path === '/dlna/discover') { dlnaDiscover(function (servers) { answer(null, { servers: servers }); }); return; }
4735
+ var q = davQ(query), f = dlnaOf(q), rel = dlnaRel(q.p);
4736
+ if (!f || rel === null) { send(res, 400, 'text/plain', 'not a media server in the home network'); return; }
4737
+ if (path === '/dlna/list') { dlnaDirId(f.control, rel, function (err, id) { if (err) { answer(err); return; } dlnaFolder(f.control, rel, id, function (e2, entries) { answer(e2, e2 ? null : { entries: entries }); }); }); return; }
4738
+ if (path === '/dlna/walk') { var st = { cancelled: false }; leaving.push(function () { st.cancelled = true; }); dlnaWalk(f.control, st, answer); return; }
4739
+ if (path === '/dlna/open') { send(res, 200, 'application/json', JSON.stringify({ ticket: netTicket('dlna', f) })); return; }
4740
+ if (path === '/dlna/sub' || path === '/dlna/mi') {
4741
+ var sub = path === '/dlna/sub';
4742
+ if (!(sub ? SUB_EXT : VIDEO_EXT).test(rel)) { send(res, 400, 'text/plain', 'not a ' + (sub ? 'subtitle file' : 'video') + ' on the server'); return; }
4743
+ dlnaFileUrl(f.control, rel, function (err, url) {
4744
+ if (err || !dlnaLanUrl(url)) { send(res, err && err.status === 404 ? 404 : 502, 'text/plain', 'failed: ' + ((err && err.message) || 'a link off the server')); return; }
4745
+ if (sub) {
4746
+ leaving.push(liveGet(url, { ua: 'StremioK' }, FS_SUB_MAX, function (e2, buf) {
4747
+ if (e2) { send(res, 502, 'text/plain', 'failed: ' + (e2.message || 'unknown')); return; }
4748
+ send(res, 200, 'text/plain; charset=utf-8', decodeText(buf));
4749
+ }));
4750
+ return;
4751
+ }
4752
+ var stops = [], stop = mediaInfo(miHttpReader(url, { ua: 'StremioK' }, true, stops), function (e3, r) {
4753
+ stops.forEach(function (x) { try { x(); } catch (e) {} });
4754
+ if (e3) { send(res, e3.status && e3.status < 600 ? e3.status : 502, 'text/plain', 'failed: ' + (e3.message || 'unknown')); return; }
4755
+ send(res, 200, 'application/json', JSON.stringify(r));
4756
+ });
4757
+ if (stop) { leaving.push(stop); }
4758
+ });
4759
+ return;
4760
+ }
4761
+ send(res, 404, 'text/plain', 'not found');
4762
+ }
4763
+
4764
+ // ---- Network files for the player: /net/<ticket>/f?p=<path> ----
4765
+ // The TV's player can't send a sign-in a header carries (or a Digest one at all), nor speak SMB:
4766
+ // such a folder's file plays through the service. StremioK asks for a ticket (/dav/open, with the
4767
+ // folder and its sign-in in headers as usual) and gives the player /net/<ticket>/f?p=…; the
4768
+ // ticket, random and kept only in memory, stands for that folder and its sign-in, NET_TICKET_IDLE_MS
4769
+ // unused at most, NET_TICKETS_MAX of them (the oldest dropped). Nothing else is reachable with
4770
+ // it: a video file's path under that folder.
4771
+ var NET_TICKETS_MAX = 16, NET_TICKET_IDLE_MS = 6 * 3600000, _netTickets = {};
4772
+ function netTicket(kind, f) {
4773
+ var now = Date.now(), ids = Object.keys(_netTickets);
4774
+ ids.forEach(function (id) { if (now - _netTickets[id].last > NET_TICKET_IDLE_MS) { delete _netTickets[id]; } });
4775
+ ids = Object.keys(_netTickets);
4776
+ for (var i = 0; i < ids.length; i++) { var t = _netTickets[ids[i]]; if (t.kind === kind && t.key === netKey(kind, f)) { t.f = f; t.last = now; return ids[i].slice(2); } } // (the same folder and sign-in: its ticket)
4777
+ if (ids.length >= NET_TICKETS_MAX) { ids.sort(function (a, b) { return _netTickets[a].last - _netTickets[b].last; }); delete _netTickets[ids[0]]; }
4778
+ var id = crypto.randomBytes(16).toString('hex');
4779
+ _netTickets['t:' + id] = { kind: kind, f: f, key: netKey(kind, f), last: now }; // (prefixed, as _dlna's)
4780
+ return id;
4781
+ }
4782
+ function netKey(kind, f) { return kind + '\n' + crypto.createHash('sha256').update(JSON.stringify([f.base || f.host || f.control || '', f.share || '', f.auth || f.user || '', f.pass || '', f.cert || ''])).digest('hex'); }
4783
+ function netControl(req, res, path, query) {
4784
+ var m = /^\/net\/([0-9a-f]{32})\/f$/.exec(path), t = m && Object.prototype.hasOwnProperty.call(_netTickets, 't:' + m[1]) ? _netTickets['t:' + m[1]] : null;
4785
+ if (!t || Date.now() - t.last > NET_TICKET_IDLE_MS) { send(res, 404, 'text/plain', 'not found'); return; }
4786
+ t.last = Date.now();
4787
+ var q = davQ(query), rel = String(q.p || '');
4788
+ if (!VIDEO_EXT.test(rel)) { send(res, 400, 'text/plain', 'not a video in the folder'); return; }
4789
+ if (t.kind === 'dav') {
4790
+ var url = davUrl(t.f, rel);
4791
+ if (!url) { send(res, 400, 'text/plain', 'not a path in the folder'); return; }
4792
+ davFileRelay(t.f, url, req, res);
4793
+ return;
4794
+ }
4795
+ if (t.kind === 'smb') { smbFileRelay(t.f, rel, req, res); return; }
4796
+ if (t.kind === 'dlna') { var dr = dlnaRel(rel); if (dr === null) { send(res, 400, 'text/plain', 'not a path on the server'); return; } dlnaFileRedirect(t.f, dr, res); return; }
4797
+ send(res, 404, 'text/plain', 'not found');
4798
+ }
4799
+ // A file in a WebDAV folder, relayed to the player: its byte range asked for with the folder's
4800
+ // sign-in (Basic or Digest), redirects on the same server only, its certificate as trusted.
4801
+ var DAV_FILE_MS = 20000;
4802
+ function davFileRelay(f, url, req, res) {
4803
+ var range = /^bytes=\d*-\d*$/.test(String(req.headers.range || '')) ? String(req.headers.range) : '';
4804
+ var r = null, gone = false, digested = false;
4805
+ function stop() { gone = true; clearTimeout(timer); try { if (r) { r.abort(); } } catch (e) {} }
4806
+ res.on('close', stop);
4807
+ function fail(code, why) { if (gone) { return; } if (!res.headersSent) { send(res, code, 'text/plain', 'failed: ' + why); } else { try { res.end(); } catch (e) {} } stop(); }
4808
+ var timer = setTimeout(function () { if (!res.headersSent) { fail(504, 'no answer in ' + (DAV_FILE_MS / 1000) + ' s'); } }, DAV_FILE_MS);
4809
+ function go(u, hops) {
4810
+ var pu;
4811
+ try { pu = urllib.parse(u); } catch (e) { fail(400, 'bad address'); return; }
4812
+ if ((pu.protocol !== 'http:' && pu.protocol !== 'https:') || !dlHostOk(pu.hostname)) { fail(400, 'an address it can\'t reach'); return; }
4813
+ var h = { 'User-Agent': 'StremioK', 'Accept': '*/*' };
4814
+ if (range) { h.Range = range; }
4815
+ if (f.auth) { h.Authorization = davAuthFor(f, 'GET', pu.path); }
4816
+ var opts = { hostname: pu.hostname, port: pu.port, path: pu.path, method: 'GET', headers: h };
4817
+ if (pu.protocol === 'https:') {
4818
+ if (f.cert) { opts.ca = [f.cert]; opts.checkServerIdentity = function () { return undefined; }; opts.agent = false; }
4819
+ else if (caList().length) { opts.ca = caList(); }
4820
+ }
4821
+ try {
4822
+ r = (pu.protocol === 'https:' ? https : http).request(opts, function (resp) {
4823
+ if (gone) { resp.resume(); return; }
4824
+ var sc = resp.statusCode;
4825
+ if (sc >= 300 && sc < 400 && resp.headers.location && hops < 4) {
4826
+ resp.resume();
4827
+ var np = null;
4828
+ try { np = urllib.parse(urllib.resolve(u, String(resp.headers.location))); } catch (e) { np = null; }
4829
+ if (!np || !davUnder(f, np)) { fail(502, 'it sent StremioK to another address: not followed'); return; }
4830
+ go(urllib.format(np), hops + 1);
4831
+ return;
4832
+ }
4833
+ if (sc === 401 && !digested && davDigestLearn(f, resp.headers['www-authenticate'])) { resp.resume(); digested = true; go(u, hops); return; }
4834
+ if (sc !== 200 && sc !== 206) { resp.resume(); fail(sc >= 400 && sc < 600 ? sc : 502, 'HTTP ' + sc); return; }
4835
+ clearTimeout(timer);
4836
+ var out = { 'Content-Type': String(resp.headers['content-type'] || 'application/octet-stream'), 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Accept-Ranges': 'bytes' };
4837
+ if (resp.headers['content-length']) { out['Content-Length'] = resp.headers['content-length']; }
4838
+ if (resp.headers['content-range']) { out['Content-Range'] = resp.headers['content-range']; }
4839
+ res.writeHead(sc, out);
4840
+ resp.on('data', function (c) {
4841
+ if (gone) { return; }
4842
+ if (!res.write(c)) { resp.pause(); res.once('drain', function () { if (!gone) { resp.resume(); } }); }
4843
+ });
4844
+ resp.on('end', function () { if (!gone) { try { res.end(); } catch (e) {} } });
4845
+ resp.on('error', function () { fail(502, 'the folder stopped sending'); });
4846
+ });
4847
+ guardSelf(r, function () { fail(400, 'an address it can\'t reach'); });
4848
+ r.on('error', function (e) { fail(502, (e && e.message) || 'network error'); });
4849
+ r.end();
4850
+ } catch (e) { fail(400, 'bad address'); }
4851
+ }
4852
+ go(url, 0);
3268
4853
  }
3269
4854
  function davControl(req, res, path, query, leaving) {
3270
4855
  if (!entryAllowed(req, query)) { send(res, 403, 'text/plain', 'not allowed (token)'); return; }
@@ -3276,6 +4861,21 @@ function davControl(req, res, path, query, leaving) {
3276
4861
  davProblem(f, err, function (p) { send(res, 200, 'application/json', JSON.stringify(p)); });
3277
4862
  }
3278
4863
  if (path === '/dav/list') { leaving.push(davList(f, q.p, answer)); return; }
4864
+ if (path === '/dav/open') { // a ticket the player's link carries (see /net/)
4865
+ send(res, 200, 'application/json', JSON.stringify({ ticket: netTicket('dav', f) }));
4866
+ return;
4867
+ }
4868
+ if (path === '/dav/mi') { // what's in a file there, from its header (see mediaInfo)
4869
+ var mu = davUrl(f, q.p), mstops = [];
4870
+ if (!mu || !VIDEO_EXT.test(String(q.p || ''))) { send(res, 400, 'text/plain', 'not a video in the folder'); return; }
4871
+ var stopDm = mediaInfo(miDavReader(f, mu, mstops), function (err, r) {
4872
+ mstops.forEach(function (x) { try { x(); } catch (e) {} });
4873
+ if (err) { send(res, err.status === 400 ? 400 : 502, 'text/plain', 'failed: ' + (err.message || 'unknown')); return; }
4874
+ send(res, 200, 'application/json', JSON.stringify(r));
4875
+ });
4876
+ if (stopDm) { leaving.push(stopDm); }
4877
+ return;
4878
+ }
3279
4879
  if (path === '/dav/sub') {
3280
4880
  leaving.push(davSub(f, q.p, function (err, text) {
3281
4881
  if (err) { send(res, err.status === 400 ? 400 : 502, 'text/plain', 'failed: ' + (err.message || 'unknown')); return; }
@@ -4465,9 +6065,9 @@ function epgControl(req, res, path, query) {
4465
6065
  var ENTRY_PORT = PORT + 10, ENTRY_MS = 5 * 60 * 1000, ENTRY_IDLE_MS = 30000, ENTRY_MAX = 8192;
4466
6066
  // A configuration file: pasted on the import's page (CONFIG_MAX, sent %-encoded: 3 times that), or
4467
6067
  // given by the TV to the export's page (GIVE_MAX, POSTed to /entry/give), shown to copy or download.
4468
- var CONFIG_MAX = 262144, GIVE_MAX = 262144;
6068
+ var CONFIG_MAX = 1572864, GIVE_MAX = 1572864; // (1.5 MB: a file with your history too; the page reads it as JSON, 2 MB at most)
4469
6069
  var ENTRY_OPEN_MAX = 2, ENTRY_OPENS = 12, ENTRY_CONNECTIONS = 8, ENTRY_VISIT_MS = 20000, ENTRY_QUIET_MS = 10000;
4470
- var ENTRY_TITLES = { link: 'Play a link on StremioK', addon: 'Add an addon to StremioK', playlist: 'Add an IPTV playlist to StremioK', config: 'Import a configuration file into StremioK', give: 'Your StremioK configuration',
6070
+ var ENTRY_TITLES = { link: 'Play a link on StremioK', addon: 'Add an addon to StremioK', playlist: 'Add an IPTV playlist to StremioK', config: 'Import a configuration file into StremioK', give: 'Your StremioK configuration', givelog: 'Your StremioK logs',
4471
6071
  search: 'Search on StremioK', youtube: 'Add a YouTube catalog to StremioK', aiom: 'Your AIOManager address for StremioK', aiomkey: 'Your AIOManager API key for StremioK',
4472
6072
  server: 'Your streaming server’s address for StremioK', mac: 'Your Stalker portal’s MAC address for StremioK', webdav: 'Your network folder’s address for StremioK',
4473
6073
  jellyfin: 'Your media server’s address for StremioK', plugins: 'Add a Nuvio plugin repository to StremioK' };
@@ -4516,14 +6116,14 @@ function entryControl(req, res, path, query, body) {
4516
6116
  var now = Date.now();
4517
6117
  _entryOpened = _entryOpened.filter(function (x) { return now - x < 60000; });
4518
6118
  if (_entryOpened.length >= ENTRY_OPENS) { send(res, 429, 'text/plain', 'too many, try again in a minute'); return; }
4519
- var wm = /(?:^|&)what=([a-z]{1,12})(?:&|$)/.exec(query || ''), what = path === '/entry/give' ? 'give' : wm && ENTRY_TITLES[wm[1]] && wm[1] !== 'give' ? wm[1] : 'link';
6119
+ var wm = /(?:^|&)what=([a-z]{1,12})(?:&|$)/.exec(query || ''), what = path === '/entry/give' ? (/(?:^|&)kind=logs(?:&|$)/.test(query || '') ? 'givelog' : 'give') : wm && ENTRY_TITLES[wm[1]] && !/^give/.test(wm[1]) ? wm[1] : 'link'; // (an export: a configuration, or the logs)
4520
6120
  var ip = lanAddress();
4521
6121
  if (!ip) { send(res, 503, 'text/plain', 'no home network address'); return; }
4522
6122
  _entryOpened.push(now);
4523
6123
  var open = Object.keys(_entries).sort(function (a, b) { return _entries[a].at - _entries[b].at; });
4524
6124
  while (open.length >= ENTRY_OPEN_MAX) { entryDrop(open.shift(), true); } // (the oldest goes)
4525
6125
  var t = crypto.randomBytes(16).toString('hex');
4526
- _entries[t] = { what: what, text: null, sent: false, at: now, timer: setTimeout(function () { entryDrop(t); }, ENTRY_MS), idle: null, give: what === 'give' ? String(body) : null, seen: false };
6126
+ _entries[t] = { what: what, text: null, sent: false, at: now, timer: setTimeout(function () { entryDrop(t); }, ENTRY_MS), idle: null, give: /^give/.test(what) ? String(body) : null, seen: false };
4527
6127
  entryIdle(t);
4528
6128
  var opened = function () { send(res, 200, 'application/json', JSON.stringify({ url: 'http://' + ip + ':' + ENTRY_PORT + '/e/' + t, token: t, expires: ENTRY_MS })); };
4529
6129
  if (_entryServer) { opened(); return; }
@@ -4565,17 +6165,20 @@ function entryHtml(title, body) {
4565
6165
  function entryPage(req, res) {
4566
6166
  try {
4567
6167
  res.setHeader('Cache-Control', 'no-store');
4568
- var m = /^\/e\/([0-9a-f]{32})(\/stremiok\.txt)?$/.exec(String(req.url || '')), e = m && _entries[m[1]];
6168
+ var m = /^\/e\/([0-9a-f]{32})(\/stremiok(?:-logs)?\.txt)?$/.exec(String(req.url || '')), e = m && _entries[m[1]];
4569
6169
  if (!e || e.sent) { send(res, 404, 'text/plain', 'Not here (it was used, or the TV closed it)'); return; }
4570
6170
  var title = ENTRY_TITLES[e.what];
4571
6171
  if (e.give !== null) { // (an export: the file to copy, or download)
4572
6172
  if (req.method !== 'GET') { send(res, 405, 'text/plain', 'GET only'); return; }
4573
6173
  e.seen = true;
4574
- if (m[2]) { res.setHeader('Content-Disposition', 'attachment; filename="stremiok.txt"'); send(res, 200, 'text/plain; charset=utf-8', e.give); return; }
6174
+ var logs = e.what === 'givelog', fname = logs ? 'stremiok-logs.txt' : 'stremiok.txt';
6175
+ if (m[2]) { if (m[2] !== '/' + fname) { send(res, 404, 'text/plain', 'Not here'); return; } res.setHeader('Content-Disposition', 'attachment; filename="' + fname + '"'); send(res, 200, 'text/plain; charset=utf-8', e.give); return; }
4575
6176
  var esc = e.give.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
4576
- send(res, 200, 'text/html; charset=utf-8', entryHtml(title, '<p>It holds your addon links, playlist logins, API keys and MAC addresses: keep it somewhere private. To restore it: Settings › Content › Import configuration file, ▣ From your phone, then choose this file there (or paste it).</p>' +
6177
+ send(res, 200, 'text/html; charset=utf-8', entryHtml(title, (logs ? '<p>StremioK\'s recent problems and how long it took to start, with its version and the TV\'s. Keys and passwords are masked; still, look it over before sharing it publicly.</p>' +
6178
+ '<p>To report a problem: open an issue at <a href="https://github.com/Kepler75/StremioK/issues">github.com/Kepler75/StremioK/issues</a>, say what you did, what you expected and what happened instead, and attach this file (Download).</p>'
6179
+ : '<p>It holds your addon links, playlist logins, API keys and MAC addresses: keep it somewhere private. To restore it: Settings › Content › Import configuration file, ▣ From your phone, then choose this file there (or paste it).</p>') +
4577
6180
  '<textarea id="f" readonly rows="12">' + esc + '</textarea><button type="button" onclick="var f=document.getElementById(\'f\');f.focus();f.select();try{document.execCommand(\'copy\');this.textContent=\'Copied\';}catch(x){}">Copy</button>' +
4578
- '<a href="/e/' + m[1] + '/stremiok.txt" download="stremiok.txt"><button type="button">Download</button></a><p>It came over your home network <b>unencrypted</b>. This page closes when the TV stops showing its code.</p>'));
6181
+ '<a href="/e/' + m[1] + '/' + fname + '" download="' + fname + '"><button type="button">Download</button></a><p>It came over your home network <b>unencrypted</b>. This page closes when the TV stops showing its code.</p>'));
4579
6182
  return;
4580
6183
  }
4581
6184
  if (m[2]) { send(res, 404, 'text/plain', 'Not here'); return; }