librespot: Connection reset by peer (os error 104)

Describe the bug

Librespot keeps crashing on random intervals. I implemented the 0.0.0.0 apresolve.spotify.com bypass in /etc/hosts, but now this issue just replaced the other one: https://github.com/librespot-org/librespot/issues/1322

To reproduce

  1. Launch librespot with
stream = spotify:///librespot?name=Spotify&devicename=HA_Snapcast&bitrate=320&volume=100&cache=/data/librespot&cache-size-limit=2G&autoplay=true&params=--disable-discovery
  1. Start playing media
  2. Crashes on random intervals

Log

... SNIP ...
2024-09-16 12-09-53.469 [Error] (librespot_core::session) Connection reset by peer (os error 104)
2024-09-16 12-09-53.469 [Error] (librespot_connect::spirc) subscription terminated
2024-09-16 12-09-53.469 [Error] (librespot_playback::player) Unable to load audio item: MercuryError
2024-09-16 12-09-53.475 [Warn] (librespot) Spirc shut down unexpectedly
2024-09-16 12-09-53.475 [Warn] (librespot_core::apresolve) Failed to resolve Access Point: error trying to connect: tcp connect error: Connection refused (os error 111)
2024-09-16 12-09-53.475 [Warn] (librespot_core::apresolve) Using fallback "ap.spotify.com:443"
2024-09-16 12-09-53.475 [Info] (librespot_core::session) Connecting to AP "ap.spotify.com:443"
2024-09-16 12-09-53.811 [Info] (librespot_core::session) Authenticated as "x" !
2024-09-16 12-09-53.812 [Info] (librespot_playback::mixer::softmixer) Mixing with softvol and volume control: Log(60.0)
... SNIP ...

Host (what you are running librespot on):

  • OS: Debian container, through Snapcast
  • Platform: HAOS x86

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 15
  • Comments: 52 (30 by maintainers)

Most upvoted comments

It seems to be getting worse for me… this evening it is giving me the error almost every 30min… is there any way to debug this?

@rwjack @artenverho @herrernst @ius @tla44 could you test whether #1357 fixes the issue for you?

@rwjack @artenverho @herrernst @ius @tla44 could you test whether #1357 fixes the issue for you?

I was able to keep librespot running for 7h+ with that patch applied without a single reconnect.

I’ll follow up with some A/B testing to be sure (unless enough others confirm it works for them).

There’s a revised implementation of the modified keep-alive handling in #1359. It should behave the same as #1357, but it’d be great if any of you could give it a quick test as well!

What I’m seeing is (Spotify Desktop on Linux)

Ping // Server -> Client
// 60s
Pong // Client -> Server
PongAck // Server -> Client
// 60s
// go to beginning

i.e. the sequence is always the same, even after start-up.

I could open a PR with a quick & dirty fix, but I can’t easily test it myself: The disconnects don’t happen so frequently for me right now, so it’s hard to say whether there’s any difference (it might run for half an hour without connection resets).

EDIT: The Pong payload seems to be always zero.

Thanks for this PR.

Tested with https://github.com/librespot-org/librespot/pull/1359 I no longer have os error 104 .

But, now, even when I don’t listen music, I get a os error 107. I don’t know if this is related to this PR, or a network issue, or something else. To my knowledge, I never had this error before.

I’m running 4 instances of librespot with snapcast, on a VM machine (Proxmox VE 8.1)

Here is a log when error happens in the night, when nobody is listening music:

root@snapcast:~# service snapserver status
● snapserver.service - Snapcast server
     Loaded: loaded (/lib/systemd/system/snapserver.service; enabled; vendor preset: enabled)
     Active: active (running) since Tue 2024-10-08 10:39:04 CEST; 1 day 22h ago
       Docs: man:snapserver(1)
   Main PID: 32443 (snapserver)
      Tasks: 23 (limit: 4661)
     Memory: 44.4M
        CPU: 18min 19.128s
     CGroup: /system.slice/snapserver.service
             ├─32443 /usr/bin/snapserver --logging.sink=system --server.datadir=/var/lib/snapserver
             ├─32446 /usr/local/bin/librespot --cache-size-limit=2G --name Salon --bitrate 320 --backend pipe --cache /var/cache/librespot/steph --initial-volume 90 --onevent /home/steph/onevent salon --autoplay on --verbose
             ├─32449 /usr/local/bin/librespot --cache-size-limit=2G --name Chambre Steph --bitrate 320 --backend pipe --cache /var/cache/librespot/steph --initial-volume 90 --onevent /home/steph/onevent chambresteph --autoplay on --verb>
             ├─32452 /usr/local/bin/librespot --cache-size-limit=2G --name Bureau Steph --bitrate 320 --backend pipe --cache /var/cache/librespot/steph --initial-volume 90 --onevent /home/steph/onevent bureausteph --autoplay on --verbose
             └─32455 /usr/local/bin/librespot --cache-size-limit=2G --name 1erEtage --bitrate 320 --backend pipe --cache /var/cache/librespot/steph --initial-volume 90 --onevent /home/steph/onevent etage1 --autoplay on --verbose

oct. 10 02:48:48 snapcast snapserver[32443]: remote update selected, but none received
oct. 10 02:48:48 snapcast snapserver[32443]: Spirc shut down unexpectedly
oct. 10 02:48:48 snapcast snapserver[32443]: Transport endpoint is not connected (os error 107)
oct. 10 02:48:48 snapcast snapserver[32443]: Connecting to AP "ap-gew1.spotify.com:4070"
oct. 10 02:48:48 snapcast snapserver[32443]: Authenticated as '******' !
oct. 10 02:48:48 snapcast snapserver[32443]: Country: "FR"
oct. 10 04:43:43 snapcast snapserver[32443]: Error reading message header of length 0: End of file
oct. 10 04:43:44 snapcast snapserver[32443]: onDisconnect: 832d72b9-3c9a-4cf7-abcb-846ddc94f933
oct. 10 04:43:45 snapcast snapserver[32443]: StreamServer::NewConnection: 192.168.0.104
oct. 10 04:43:45 snapcast snapserver[32443]: Hello from 832d72b9-3c9a-4cf7-abcb-846ddc94f933, host: SHIELD Android TV, v0.28.0, ClientName: Snapclient, OS: Android 11, Arch: arm64-v8a, Protocol version: 2

There’s a revised implementation of the modified keep-alive handling in #1359. It should behave the same as #1357, but it’d be great if any of you could give it a quick test as well!

Had already spotted it and it’s been running at least as well as the v1 for me for the past two days.

Got this built and running for my LibreElec/kodi setup on a rpi4 and it has been working flawlessly for several hours today. Thank you for the fix @wisp3rwind ❤️

Thanks in particular also to @kingosticks for the initial diagnosis!

Excellent, I missed that. Do you want to PR those spotify-analyze fixes too?

Oh, that’s why I also updated dump.c: The patch that is applied to the executable affects several processes that concurrently write to the same file, corrupting it (only one process actually communicates with the server, but all of them write the pcap header). You’ll have to make again and collect new dumps. It will now write to dump-<PID>.pcap files. Select the right one for analysis by file size.

Ideally do this on Linux/mac using spotify-analyze to get a better idea.

FYI I couldn’t get it to work with latest version of wireshark but maybe someone else will have more luck.

Here's a patch for Wireshark 4.2:
From 2a0450edab4fff17cd0e4479e30a0fcf35d680dc Mon Sep 17 00:00:00 2001
From: wisp3rwind <17089248+wisp3rwind@users.noreply.github.com>
Date: Mon, 30 Sep 2024 17:20:21 +0200
Subject: [PATCH] fixes for recent spotify/wireshark

---
 dissect/dissect.sh                            |  2 +-
 .../protobuf_dissector/modules/ast/ast.lua    |  4 +-
 .../protobuf_dissector/modules/compiler.lua   |  4 +-
 .../modules/front_end/cursor.lua              |  4 +-
 .../modules/front_end/file_reader.lua         |  6 +--
 .../modules/front_end/lexer.lua               | 14 +++---
 .../modules/front_end/parser.lua              |  4 +-
 .../modules/front_end/token.lua               |  4 +-
 dissect/protobuf_dissector/modules/prefs.lua  | 10 ++++-
 dissect/protobuf_dissector/modules/syntax.lua |  4 +-
 dissect/protobuf_dissector/protobuf.lua       |  3 +-
 dissect/spotify.lua                           | 44 ++++++++++++++++---
 dump/dump.c                                   | 10 ++++-
 13 files changed, 80 insertions(+), 33 deletions(-)

diff --git a/dissect/dissect.sh b/dissect/dissect.sh
index d05fdf3..f00a708 100755
--- a/dissect/dissect.sh
+++ b/dissect/dissect.sh
@@ -1,7 +1,7 @@
 #!/usr/bin/env bash
 set -eux
 
-exec wireshark-gtk $1 \
+exec wireshark $1 \
     -X lua_script:protobuf_dissector/protobuf.lua \
     -X lua_script:spotify.lua \
     -X lua_script:mercury.lua \
diff --git a/dissect/protobuf_dissector/modules/ast/ast.lua b/dissect/protobuf_dissector/modules/ast/ast.lua
index 2eb4824..76fb15b 100644
--- a/dissect/protobuf_dissector/modules/ast/ast.lua
+++ b/dissect/protobuf_dissector/modules/ast/ast.lua
@@ -62,8 +62,8 @@ if not _G['protbuf_dissector'] then return end
 
 
 -- make sure wireshark is new enough
-if not GRegex then
-    return nil, "Wireshark is too old: no GRegex library"
+if not rex_pcre2 then
+    return nil, "Wireshark is too old: no rex_pcre2 library"
 end
 
 
diff --git a/dissect/protobuf_dissector/modules/compiler.lua b/dissect/protobuf_dissector/modules/compiler.lua
index 6f355dc..d964377 100644
--- a/dissect/protobuf_dissector/modules/compiler.lua
+++ b/dissect/protobuf_dissector/modules/compiler.lua
@@ -32,8 +32,8 @@ if not _G['protbuf_dissector'] then return end
 
 
 -- make sure wireshark is new enough
-if not GRegex then
-    return nil, "Wireshark is too old: no GRegex library"
+if not rex_pcre2 then
+    return nil, "Wireshark is too old: no rex_pcre2 library"
 end
 
 
diff --git a/dissect/protobuf_dissector/modules/front_end/cursor.lua b/dissect/protobuf_dissector/modules/front_end/cursor.lua
index b4cd3c9..134b04c 100644
--- a/dissect/protobuf_dissector/modules/front_end/cursor.lua
+++ b/dissect/protobuf_dissector/modules/front_end/cursor.lua
@@ -94,8 +94,8 @@ function Cursor:nextLine()
 end
 
 
-local wspace_rgx = GRegex.new("^([ \t]++)|^(\n)", "s")
-local chunk_rgx  = GRegex.new("^([^\n]++)|^(\n)", "s")
+local wspace_rgx = rex_pcre2.new("^([ \t]++)|^(\n)", "s")
+local chunk_rgx  = rex_pcre2.new("^([^\n]++)|^(\n)", "s")
 local len = string.len
 local sub = string.sub
 
diff --git a/dissect/protobuf_dissector/modules/front_end/file_reader.lua b/dissect/protobuf_dissector/modules/front_end/file_reader.lua
index 6bdc90a..fb086f2 100644
--- a/dissect/protobuf_dissector/modules/front_end/file_reader.lua
+++ b/dissect/protobuf_dissector/modules/front_end/file_reader.lua
@@ -24,8 +24,8 @@ if not _G['protbuf_dissector'] then return end
 
 
 -- make sure wireshark is new enough
-if not GRegex then
-    return nil, "Wireshark is too old: no GRegex library"
+if not rex_pcre2 then
+    return nil, "Wireshark is too old: no rex_pcre2 library"
 end
 
 
@@ -46,7 +46,7 @@ end
 function FileReader:read(name)
 end
 
-local filepath_rgx = GRegex.new("^(.*)([^/\\\\]+)$", "U")
+local filepath_rgx = rex_pcre2.new("^(.*)([^/\\\\]+)$", "U")
 
 
 --------------------------------------------------------------------------------
diff --git a/dissect/protobuf_dissector/modules/front_end/lexer.lua b/dissect/protobuf_dissector/modules/front_end/lexer.lua
index 25504be..460f027 100644
--- a/dissect/protobuf_dissector/modules/front_end/lexer.lua
+++ b/dissect/protobuf_dissector/modules/front_end/lexer.lua
@@ -50,8 +50,8 @@ if not _G['protbuf_dissector'] then return end
 
 
 -- make sure wireshark is new enough
-if not GRegex then
-    return nil, "Wireshark is too old: no GRegex library"
+if not rex_pcre2 then
+    return nil, "Wireshark is too old: no rex_pcre2 library"
 end
 
 local Settings    = require "settings"
@@ -83,7 +83,7 @@ function Lexer:generateVariableMatchPatterns()
     for _, token in ipairs(self.Syntax.token_info.VARIABLE) do
         if not token.value then
             dprint2("creating new variable regex for: ", token.ttype)
-            tbl[token.ttype] = GRegex.new("^" .. token.pattern .. "$")
+            tbl[token.ttype] = rex_pcre2.new("^" .. token.pattern .. "$")
         end
     end
     self.variable_token_regexes = tbl
@@ -97,7 +97,7 @@ function Lexer:generateStringMatchPatterns()
         for _, token in ipairs(self.Syntax.token_info[category]) do
             if not token.value then
                 dprint2("creating new string regex for: ", token.ttype)
-                tbl[token.ttype] = GRegex.new("^" .. token.pattern .. "$")
+                tbl[token.ttype] = rex_pcre2.new("^" .. token.pattern .. "$")
             end
         end
     end
@@ -112,7 +112,7 @@ function Lexer:generateSkipPatterns()
         for _, token in ipairs(self.Syntax.token_info[category]) do
             if token.skip then
                 dprint2("creating new skip regex for: ", token.ttype)
-                tbl[token.ttype] = GRegex.new(token.skip, token.skip_flags)
+                tbl[token.ttype] = rex_pcre2.new(token.skip, token.skip_flags)
                 if not tbl[token.ttype] then
                     error("Could not compile regex for: " .. token.ttype)
                 end
@@ -173,7 +173,7 @@ function Lexer:compilePatterns()
     local t = {}
     for ttype, str in pairs(self.pattern_strings) do
         -- Gregex will raise a Lua error if this doesn't succeed
-        t[ttype] = GRegex.new(str)
+        t[ttype] = rex_pcre2.new(str)
     end
     self.pattern = t
 end
@@ -226,7 +226,7 @@ function Lexer:tokenize(chunk, filename)
     -- normally we'd use Gregex.gmatch() in a for-loop to do this, but we need to
     -- skip quoted strings inside the for-loop, and that can't be done with gmatch;
     -- so we're going to do it the slower way by creating lots of substrings :(
-    -- also, GRegex.match() doesn't consider subsequent iterations to match a
+    -- also, rex_pcre2.match() doesn't consider subsequent iterations to match a
     -- pattern with a "^" anchor, which is unfortunate, so by creating substrings
     -- we get to use "^" to prevent skipping unmatched words/tokens
 
diff --git a/dissect/protobuf_dissector/modules/front_end/parser.lua b/dissect/protobuf_dissector/modules/front_end/parser.lua
index d03e1a9..7799034 100644
--- a/dissect/protobuf_dissector/modules/front_end/parser.lua
+++ b/dissect/protobuf_dissector/modules/front_end/parser.lua
@@ -40,8 +40,8 @@ if not _G['protbuf_dissector'] then return end
 
 
 -- make sure wireshark is new enough
-if not GRegex then
-    return nil, "Wireshark is too old: no GRegex library"
+if not rex_pcre2 then
+    return nil, "Wireshark is too old: no rex_pcre2 library"
 end
 
 
diff --git a/dissect/protobuf_dissector/modules/front_end/token.lua b/dissect/protobuf_dissector/modules/front_end/token.lua
index 5f2b32c..259a9ae 100644
--- a/dissect/protobuf_dissector/modules/front_end/token.lua
+++ b/dissect/protobuf_dissector/modules/front_end/token.lua
@@ -93,8 +93,8 @@ function Token:isNativeType()
 end
 
 
-local hex_rgx = GRegex.new("^0[xX]([a-fA-F0-9]+)$")
-local oct_rgx = GRegex.new("^0([0-7]+)$")
+local hex_rgx = rex_pcre2.new("^0[xX]([a-fA-F0-9]+)$")
+local oct_rgx = rex_pcre2.new("^0([0-7]+)$")
 
 
 function Token:convertToNumber()
diff --git a/dissect/protobuf_dissector/modules/prefs.lua b/dissect/protobuf_dissector/modules/prefs.lua
index ba5cdda..28f66f8 100644
--- a/dissect/protobuf_dissector/modules/prefs.lua
+++ b/dissect/protobuf_dissector/modules/prefs.lua
@@ -14,6 +14,12 @@
 if not _G['protbuf_dissector'] then return end
 
 
+-- make sure wireshark is new enough
+if not rex_pcre2 then
+    return nil, "Wireshark is too old: no rex_pcre2 library"
+end
+
+
 local Settings = require "settings"
 local dprint   = Settings.dprint
 local dprint2  = Settings.dprint2
@@ -24,10 +30,10 @@ local derror   = Settings.derror
 local Prefs = {}
 
 
-local range_rgx = GRegex.new("([0-9]+)\\s*(?:-\\s*([0-9]+))?")
+local range_rgx = rex_pcre2.new("([0-9]+)\\s*(?:-\\s*([0-9]+))?")
 local function getRange(range)
     local t = {}
-    for first, second in GRegex.gmatch(range, range_rgx) do
+    for first, second in rex_pcre2.gmatch(range, range_rgx) do
         if first then
             first = tonumber(first)
             if second then
diff --git a/dissect/protobuf_dissector/modules/syntax.lua b/dissect/protobuf_dissector/modules/syntax.lua
index 7dce9e2..9fa9738 100644
--- a/dissect/protobuf_dissector/modules/syntax.lua
+++ b/dissect/protobuf_dissector/modules/syntax.lua
@@ -26,8 +26,8 @@ if not _G['protbuf_dissector'] then return end
 
 
 -- make sure wireshark is new enough
-if not GRegex then
-    error("Wireshark is too old: no GRegex library - upgrade to version 1.12 or higher.")
+if not rex_pcre2 then
+    error("Wireshark is too old: no rex_pcre2 library - upgrade to version 1.12 or higher.")
 end
 
 
diff --git a/dissect/protobuf_dissector/protobuf.lua b/dissect/protobuf_dissector/protobuf.lua
index 9898c28..c38960c 100644
--- a/dissect/protobuf_dissector/protobuf.lua
+++ b/dissect/protobuf_dissector/protobuf.lua
@@ -40,7 +40,8 @@ _G['protbuf_dissector'] = {
 
 
 -- help wireshark find our modules
-package.prepend_path("modules")
+-- package.prepend_path("modules")
+package.path = __DIR__ .. __DIR_SEPARATOR__ .. "modules" .. __DIR_SEPARATOR__ .. "?.lua;" .. package.path
 
 
 -- load our settings
diff --git a/dissect/spotify.lua b/dissect/spotify.lua
index 66ab1db..78bdc80 100644
--- a/dissect/spotify.lua
+++ b/dissect/spotify.lua
@@ -28,16 +28,50 @@ function spotify.dissector(buffer, pinfo, tree)
     subtree:add(f.cmd, cmd)
     subtree:add(f.length, length)
 
-    if cmd:uint() == 0xab then
+    if false then
+    elseif cmd:uint() == 0x02 then
+        pinfo.cols.info = "SecretBlock"
+    elseif cmd:uint() == 0x04 then
+        pinfo.cols.info = "Ping: " .. payload(0, 4):uint()
+    elseif cmd:uint() == 0x08 then
+        pinfo.cols.info = "StreamChunk"
+    elseif cmd:uint() == 0x09 then
+        pinfo.cols.info = "StreamChunkRes"
+    elseif cmd:uint() == 0x0a then
+        pinfo.cols.info = "ChannelError"
+    elseif cmd:uint() == 0x0b then
+        pinfo.cols.info = "ChannelAbort"
+    elseif cmd:uint() == 0x0c then
+        pinfo.cols.info = "RequestKey: " .. payload()
+    elseif cmd:uint() == 0x0d then
+        pinfo.cols.info = "AesKey: " .. payload()
+    elseif cmd:uint() == 0x0e then
+        pinfo.cols.info = "AesKeyError"
+    elseif cmd:uint() == 0x19 then
+        pinfo.cols.info = "Image"
+    elseif cmd:uint() == 0x1b then
+        pinfo.cols.info = "CountryCode: " .. payload()
+    elseif cmd:uint() == 0x49 then
+        pinfo.cols.info = "Pong"
+    elseif cmd:uint() == 0x4a then
+        pinfo.cols.info = "PongAck"
+    elseif cmd:uint() == 0x4b then
+        pinfo.cols.info = "Pause"
+    -- elseif cmd:uint() == 0x50 then
+    --     pinfo.cols.info = "ProductInfo"
+    elseif cmd:uint() == 0x69 then
+        pinfo.cols.info = "LegacyWelcome"
+    elseif cmd:uint() == 0x76 then
+        pinfo.cols.info = "LicenseVersion"
+    elseif cmd:uint() == 0xab then
         DissectorTable.get("protobuf"):try("ClientResponseEncrypted", payload, pinfo, tree)
+        pinfo.cols.info = "Login"
     elseif cmd:uint() == 0xac then
         DissectorTable.get("protobuf"):try("APWelcome", payload, pinfo, tree)
+        pinfo.cols.info = "APWelcome"
     elseif cmd:uint() == 0xad then
         DissectorTable.get("protobuf"):try("APLoginFailed", payload, pinfo, tree)
-    elseif cmd:uint() == 0x0c then
-        pinfo.cols.info = "Req AudioKey: " .. payload()
-    elseif cmd:uint() == 0x0d then
-        pinfo.cols.info = "Got AudioKey: " .. payload()
+        pinfo.cols.info = "APLoginFailed"
     else
         DissectorTable.get("spotify.cmd"):try(cmd:uint(), payload, pinfo, tree)
     end
diff --git a/dump/dump.c b/dump/dump.c
index de486d1..3fe60c0 100644
--- a/dump/dump.c
+++ b/dump/dump.c
@@ -15,6 +15,7 @@
 #include <pthread.h>
 #include <dlfcn.h>
 #include <assert.h>
+#include <arpa/inet.h>
 
 #ifdef __APPLE__
 #include <mach-o/dyld.h>
@@ -103,11 +104,16 @@ static void find_shn_heuristic(void *text_start, size_t text_size, void **p_shn_
 }
 
 static void patch_shn(void) {
-    dump_fd = open("dump.pcap", O_CREAT | O_RDWR | O_TRUNC, 0644);
+    char *fname = (char *) malloc(64 * sizeof(char));
+    pid_t pid = getpid();
+    snprintf(fname, 64, "dump-%ld.pcap", (long) pid);
+
+    dump_fd = open(fname, O_CREAT | O_RDWR | O_TRUNC, 0644);
 
     pcap_write_header(dump_fd, PCAP_DLT_USER0);
 
-    printf("Patching ...\n");
+
+    printf("Patching ... (PID = %ld)\n", (long) pid);
 
     size_t text_size = 0;
     void *text_start = NULL;
-- 
2.46.2