From 4ad0cc86b7580459bff26857bf781be32a5d9be3 Mon Sep 17 00:00:00 2001
From: ideal <idealities@gmail.com>
Date: Sat, 14 Sep 2019 18:06:18 +0800
Subject: [PATCH] Fix for upgrade of libwebsockets 3.2.0, it removes the poll
 which breaks every second in the previous version.

Reference:
[1] https://github.com/warmcat/libwebsockets/issues/1685
[2] https://libwebsockets.org/git/libwebsockets/tree/READMEs/README.lws_sul.md
---
 src/protocol.c | 18 ++++++++++++++++++
 src/server.c   |  7 +++----
 src/server.h   |  3 +++
 3 files changed, 24 insertions(+), 4 deletions(-)

diff --git a/src/protocol.c b/src/protocol.c
index 933e1eb..f837183 100644
--- a/src/protocol.c
+++ b/src/protocol.c
@@ -161,10 +161,24 @@ cleanup:
 
     pthread_mutex_destroy(&client->mutex);
 
+#if LWS_LIBRARY_VERSION_NUMBER >= 3002000
+    lws_sul_schedule(context, 0, &client->sul_stagger, NULL, LWS_SET_TIMER_USEC_CANCEL);
+#endif
+
     // remove from client list
     tty_client_remove(client);
 }
 
+#if LWS_LIBRARY_VERSION_NUMBER >= 3002000
+void
+stagger_callback(lws_sorted_usec_list_t *sul) {
+    struct tty_client *client = lws_container_of(sul, struct tty_client, sul_stagger);
+
+    lws_callback_on_writable(client->wsi);
+    lws_sul_schedule(context, 0, sul, stagger_callback, 10 * LWS_US_PER_MS);
+}
+#endif
+
 void *
 thread_run_command(void *args) {
     struct tty_client *client = (struct tty_client *) args;
@@ -357,6 +371,10 @@ callback_tty(struct lws *wsi, enum lws_callback_reasons reason,
             // check if there are more fragmented messages
             if (lws_remaining_packet_payload(wsi) > 0 || !lws_is_final_fragment(wsi)) {
                 return 0;
+            } else {
+                #if LWS_LIBRARY_VERSION_NUMBER >= 3002000
+                lws_sul_schedule(context, 0, &client->sul_stagger, stagger_callback, 10);
+                #endif
             }
 
             switch (command) {
diff --git a/src/server.c b/src/server.c
index 7afa467..8e1855b 100644
--- a/src/server.c
+++ b/src/server.c
@@ -18,10 +18,6 @@
 #define TTYD_VERSION "unknown"
 #endif
 
-#if LWS_LIBRARY_VERSION_NUMBER == 3002000
-#error "libwebsockets 3.2.0 is not compatible with ttyd."
-#endif
-
 volatile bool force_exit = false;
 struct lws_context *context;
 struct tty_server *server;
@@ -497,6 +493,9 @@ main(int argc, char **argv) {
         }
         pthread_mutex_unlock(&server->mutex);
         lws_service(context, 10);
+#if LWS_LIBRARY_VERSION_NUMBER >= 3002000
+        usleep(10 * LWS_US_PER_MS);
+#endif
     }
 
     lws_context_destroy(context);
diff --git a/src/server.h b/src/server.h
index 3493839..43a2327 100644
--- a/src/server.h
+++ b/src/server.h
@@ -36,6 +36,9 @@ struct tty_client {
     int argc;
 
     struct lws *wsi;
+#if LWS_LIBRARY_VERSION_NUMBER >= 3002000
+    lws_sorted_usec_list_t sul_stagger;
+#endif
     struct winsize size;
     char *buffer;
     size_t len;
-- 
2.43.4