• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lunarmodules / copas / 30193139786

26 Jul 2026 07:37AM UTC coverage: 85.027%. Remained the same
30193139786

push

github

web-flow
chore(ci): pin rocks versions (#194)

1414 of 1663 relevant lines covered (85.03%)

72458.84 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

80.06
/src/copas.lua
1
-------------------------------------------------------------------------------
2
-- Copas - Coroutine Oriented Portable Asynchronous Services
3
--
4
-- A dispatcher based on coroutines that can be used by TCP/IP servers.
5
-- Uses LuaSocket as the interface with the TCP/IP stack.
6
--
7
-- Authors: Andre Carregal, Javier Guerra, and Fabio Mascarenhas
8
-- Contributors: Diego Nehab, Mike Pall, David Burgess, Leonardo Godinho,
9
--               Thomas Harning Jr., and Gary NG
10
--
11
-- Copyright 2005-2013 - Kepler Project (www.keplerproject.org), 2015-2026 Thijs Schreijer
12
--
13
-- $Id: copas.lua,v 1.37 2009/04/07 22:09:52 carregal Exp $
14
-------------------------------------------------------------------------------
15

16
if package.loaded["socket.http"] and (_VERSION=="Lua 5.1") then     -- obsolete: only for Lua 5.1 compatibility
188✔
17
  error("you must require copas before require'ing socket.http")
×
18
end
19
if package.loaded["copas.http"] and (_VERSION=="Lua 5.1") then     -- obsolete: only for Lua 5.1 compatibility
188✔
20
  error("you must require copas before require'ing copas.http")
×
21
end
22

23
-- load either LuaSocket, or LuaSystem
24
-- note: with luasocket we don't use 'sleep' but 'select' with no sockets
25
local socket, system do
188✔
26
  if pcall(require, "socket") then
189✔
27
    -- found LuaSocket
28
    socket = require "socket"
182✔
29
  end
30

31
  -- try LuaSystem as fallback
32
  if pcall(require, "system") then
189✔
33
    system = require "system"
189✔
34
  end
35

36
  if not (socket or system) then
188✔
37
    error("Neither LuaSocket nor LuaSystem found, Copas requires at least one of them")
×
38
  end
39
end
40

41
local binaryheap = require "binaryheap"
188✔
42
local gettime = (socket or system).gettime
188✔
43
local block_sleep = (socket or system).sleep
188✔
44
local ssl -- only loaded upon demand
45

46
local core_timer_thread
47
local WATCH_DOG_TIMEOUT = 120
188✔
48
local UDP_DATAGRAM_MAX = (socket or {})._DATAGRAMSIZE or 8192
188✔
49
local TIMEOUT_PRECISION = 0.1  -- 100ms
188✔
50
local fnil = function() end
277,514✔
51

52

53
local coroutine_create = coroutine.create
188✔
54
local coroutine_running = coroutine.running
188✔
55
local coroutine_yield = coroutine.yield
188✔
56
local coroutine_resume = coroutine.resume
188✔
57
local coroutine_status = coroutine.status
188✔
58

59

60
-- nil-safe versions for pack/unpack
61
local _unpack = unpack or table.unpack
188✔
62
local unpack = function(t, i, j) return _unpack(t, i or 1, j or t.n or #t) end
1,306✔
63
local pack = function(...) return { n = select("#", ...), ...} end
1,859✔
64

65

66
local pcall = pcall
188✔
67
if _VERSION=="Lua 5.1" and not jit then     -- obsolete: only for Lua 5.1 compatibility
188✔
68
  pcall = require("coxpcall").pcall
30✔
69
  coroutine_running = require("coxpcall").running
30✔
70
end
71

72

73
if socket then
188✔
74
  -- Redefines LuaSocket functions with coroutine safe versions (pure Lua)
75
  -- (this allows the use of socket.http from within copas)
76
  local err_mt = {
182✔
77
    __tostring = function (self)
78
      return "Copas 'try' error intermediate table: '"..tostring(self[1].."'")
×
79
    end,
80
  }
81

82
  local function statusHandler(status, ...)
83
    if status then return ... end
84✔
84
    local err = (...)
30✔
85
    if type(err) == "table" and getmetatable(err) == err_mt then
30✔
86
      return nil, err[1]
30✔
87
    else
88
      error(err)
×
89
    end
90
  end
91

92
  function socket.protect(func)
182✔
93
    return function (...)
94
            return statusHandler(pcall(func, ...))
98✔
95
          end
96
  end
97

98
  function socket.newtry(finalizer)
182✔
99
    return function (...)
100
            local status = (...)
1,380✔
101
            if not status then
1,380✔
102
              pcall(finalizer or fnil, select(2, ...))
30✔
103
              error(setmetatable({ (select(2, ...)) }, err_mt), 0)
30✔
104
            end
105
            return ...
1,350✔
106
          end
107
  end
108

109
  socket.try = socket.newtry()
211✔
110
end
111

112

113
-- Setup the Copas meta table to auto-load submodules and define a default method
114
local copas do
188✔
115
  local submodules = { "ftp", "future", "http", "lock", "queue", "semaphore", "smtp", "timer" }
188✔
116
  for i, key in ipairs(submodules) do
1,692✔
117
    submodules[key] = true
1,504✔
118
    submodules[i] = nil
1,504✔
119
  end
120

121
  copas = setmetatable({},{
376✔
122
    __index = function(self, key)
123
      if submodules[key] then
248✔
124
        self[key] = require("copas."..key)
250✔
125
        submodules[key] = nil
248✔
126
        return rawget(self, key)
248✔
127
      end
128
    end,
129
    __call = function(self, ...)
130
      return self.loop(...)
6✔
131
    end,
132
  })
188✔
133
end
134

135

136
-- Meta information is public even if beginning with an "_"
137
copas._COPYRIGHT   = "Copyright (C) 2005-2013 Kepler Project, 2015-2026 Thijs Schreijer"
188✔
138
copas._DESCRIPTION = "Coroutine Oriented Portable Asynchronous Services"
188✔
139
copas._VERSION     = "Copas 4.11.0"
188✔
140

141
-- Close the socket associated with the current connection after the handler finishes
142
copas.autoclose = true
188✔
143

144
-- indicator for the loop running
145
copas.running = false
188✔
146

147
-- gettime method from either LuaSocket or LuaSystem: time in (fractional) seconds, since epoch.
148
copas.gettime = gettime
188✔
149

150
-------------------------------------------------------------------------------
151
-- Object names, to track names of thread/coroutines and sockets
152
-------------------------------------------------------------------------------
153
local object_names = setmetatable({}, {
376✔
154
  __mode = "k",
158✔
155
  __index = function(self, key)
156
    local name = tostring(key)
192✔
157
    if key ~= nil then
192✔
158
      rawset(self, key, name)
192✔
159
    end
160
    return name
192✔
161
  end
162
})
163

164
-------------------------------------------------------------------------------
165
-- Simple set implementation
166
-- adds a FIFO queue for each socket in the set
167
-------------------------------------------------------------------------------
168

169
local function newsocketset()
170
  local set = {}
564✔
171

172
  do  -- set implementation
173
    local reverse = {}
564✔
174

175
    -- Adds a socket to the set, does nothing if it exists
176
    -- @return skt if added, or nil if it existed
177
    function set:insert(skt)
564✔
178
      if not reverse[skt] then
1,398✔
179
        self[#self + 1] = skt
1,398✔
180
        reverse[skt] = #self
1,398✔
181
        return skt
1,398✔
182
      end
183
    end
184

185
    -- Removes socket from the set, does nothing if not found
186
    -- @return skt if removed, or nil if it wasn't in the set
187
    function set:remove(skt)
564✔
188
      local index = reverse[skt]
1,926✔
189
      if index then
1,926✔
190
        reverse[skt] = nil
1,392✔
191
        local top = self[#self]
1,392✔
192
        self[#self] = nil
1,392✔
193
        if top ~= skt then
1,392✔
194
          reverse[top] = index
171✔
195
          self[index] = top
171✔
196
        end
197
        return skt
1,392✔
198
      end
199
    end
200

201
  end
202

203
  do  -- queues implementation
204
    local fifo_queues = setmetatable({},{
1,128✔
205
      __mode = "k",                 -- auto collect queue if socket is gone
474✔
206
      __index = function(self, skt) -- auto create fifo queue if not found
207
        local newfifo = {}
510✔
208
        self[skt] = newfifo
510✔
209
        return newfifo
510✔
210
      end,
211
    })
212

213
    -- pushes an item in the fifo queue for the socket.
214
    function set:push(skt, itm)
564✔
215
      local queue = fifo_queues[skt]
1,302✔
216
      queue[#queue + 1] = itm
1,302✔
217
    end
218

219
    -- pops an item from the fifo queue for the socket
220
    function set:pop(skt)
564✔
221
      local queue = fifo_queues[skt]
1,224✔
222
      return table.remove(queue, 1)
1,224✔
223
    end
224

225
  end
226

227
  return set
564✔
228
end
229

230

231

232
-- Threads immediately resumable
233
local _resumable = {} do
188✔
234
  local resumelist = {}
188✔
235

236
  function _resumable:push(co)
188✔
237
    resumelist[#resumelist + 1] = co
277,181✔
238
  end
239

240
  function _resumable:clear_resumelist()
188✔
241
    local lst = resumelist
267,932✔
242
    resumelist = {}
267,932✔
243
    return lst
267,932✔
244
  end
245

246
  function _resumable:done()
188✔
247
    return resumelist[1] == nil
271,320✔
248
  end
249

250
  function _resumable:count()
188✔
251
    return #resumelist + #_resumable
×
252
  end
253

254
end
255

256

257

258
-- Similar to the socket set above, but tailored for the use of
259
-- sleeping threads
260
local _sleeping = {} do
188✔
261

262
  local heap = binaryheap.minUnique()
188✔
263
  local lethargy = setmetatable({}, { __mode = "k" }) -- list of coroutines sleeping without a wakeup time
188✔
264

265

266
  -- Required base implementation
267
  -----------------------------------------
268
  _sleeping.insert = fnil
188✔
269
  _sleeping.remove = fnil
188✔
270

271
  -- push a new timer on the heap
272
  function _sleeping:push(sleeptime, co)
188✔
273
    if sleeptime < 0 then
277,320✔
274
      lethargy[co] = true
3,222✔
275
    elseif sleeptime == 0 then
274,098✔
276
      _resumable:push(co)
364,452✔
277
    else
278
      heap:insert(gettime() + sleeptime, co)
7,252✔
279
    end
280
  end
281

282
  -- find the thread that should wake up to the time, if any
283
  function _sleeping:pop(time)
188✔
284
    if time < (heap:peekValue() or math.huge) then
373,931✔
285
      return
267,932✔
286
    end
287
    return heap:pop()
7,041✔
288
  end
289

290
  -- additional methods for time management
291
  -----------------------------------------
292
  function _sleeping:getnext()  -- returns delay until next sleep expires, or nil if there is none
188✔
293
    local t = heap:peekValue()
5,970✔
294
    if t then
5,970✔
295
      -- never report less than 0, because select() might block
296
      return math.max(t - gettime(), 0)
5,970✔
297
    end
298
  end
299

300
  function _sleeping:wakeup(co)
188✔
301
    if lethargy[co] then
3,234✔
302
      lethargy[co] = nil
3,204✔
303
      _resumable:push(co)
3,204✔
304
      return
3,204✔
305
    end
306
    if heap:remove(co) then
35✔
307
      _resumable:push(co)
12✔
308
    end
309
  end
310

311
  function _sleeping:cancel(co)
188✔
312
    lethargy[co] = nil
54✔
313
    heap:remove(co)
54✔
314
  end
315

316
  function _sleeping:cancelall()
188✔
317
    while heap:size() > 0 do heap:pop() end
×
318
    heap:insert(gettime() + TIMEOUT_PRECISION, core_timer_thread)
×
319
    -- lethargy is weak; copas's idle GC sweeps will clean it within a few steps
320
  end
321

322
  -- @param tos number of timeouts running
323
  function _sleeping:done(tos)
188✔
324
    -- return true if we have nothing more to do
325
    -- the timeout task doesn't qualify as work (fallbacks only),
326
    -- the lethargy also doesn't qualify as work ('dead' tasks),
327
    -- but the combination of a timeout + a lethargy can be work
328
    return heap:size() == 1       -- 1 means only the timeout-timer task is running
3,139✔
329
           and not (tos > 0 and next(lethargy))
2,698✔
330
  end
331

332
  -- gets number of threads in binaryheap and lethargy
333
  function _sleeping:status()
188✔
334
    local c = 0
×
335
    for _ in pairs(lethargy) do c = c + 1 end
×
336

337
    return heap:size(), c
×
338
  end
339

340
end   -- _sleeping
341

342

343

344
-------------------------------------------------------------------------------
345
-- Tracking coroutines and sockets
346
-------------------------------------------------------------------------------
347

348
local _servers = newsocketset() -- servers being handled
188✔
349
local _threads = setmetatable({}, {__mode = "k"})  -- registered threads added with addthread()
188✔
350
local _canceled = setmetatable({}, {__mode = "k"}) -- threads that are canceled and pending removal
188✔
351
local _autoclose = setmetatable({}, {__mode = "kv"}) -- sockets (value) to close when a thread (key) exits
188✔
352
local _autoclose_r = setmetatable({}, {__mode = "kv"}) -- reverse: sockets (key) to close when a thread (value) exits
188✔
353

354

355
-- for each socket we log the last read and last write times to enable the
356
-- watchdog to follow up if it takes too long.
357
-- tables contain the time, indexed by the socket
358
local _reading_log = {}
188✔
359
local _writing_log = {}
188✔
360

361
local _closed = {} -- track sockets that have been closed (list/array)
188✔
362

363
local _reading = newsocketset() -- sockets currently being read
188✔
364
local _writing = newsocketset() -- sockets currently being written
188✔
365
local _isSocketTimeout = { -- set of errors indicating a socket-timeout
188✔
366
  ["timeout"] = true,      -- default LuaSocket timeout
158✔
367
  ["wantread"] = true,     -- LuaSec specific timeout
158✔
368
  ["wantwrite"] = true,    -- LuaSec specific timeout
158✔
369
}
370

371
-------------------------------------------------------------------------------
372
-- Coroutine based socket timeouts.
373
-------------------------------------------------------------------------------
374
local user_timeouts_connect
375
local user_timeouts_send
376
local user_timeouts_receive
377
do
378
  local timeout_mt = {
188✔
379
    __mode = "k",
158✔
380
    __index = function(self, skt)
381
      -- if there is no timeout found, we insert one automatically, to block forever
382
      self[skt] = math.huge
432✔
383
      return self[skt]
432✔
384
    end,
385
  }
386

387
  user_timeouts_connect = setmetatable({}, timeout_mt)
188✔
388
  user_timeouts_send = setmetatable({}, timeout_mt)
188✔
389
  user_timeouts_receive = setmetatable({}, timeout_mt)
188✔
390
end
391

392
local useSocketTimeoutErrors = setmetatable({},{ __mode = "k" })
188✔
393

394

395
-- sto = socket-time-out
396
local sto_timeout, sto_timed_out, sto_change_queue, sto_error do
188✔
397

398
  local socket_register = setmetatable({}, { __mode = "k" })    -- socket by coroutine
188✔
399
  local operation_register = setmetatable({}, { __mode = "k" }) -- operation "read"/"write" by coroutine
188✔
400
  local timeout_flags = setmetatable({}, { __mode = "k" })      -- true if timedout, by coroutine
188✔
401

402

403
  -- The callback called when a socket timeout occurs.
404
  local function socket_callback(co)
405
    local skt = socket_register[co]
78✔
406
    local queue = operation_register[co]
78✔
407

408
    -- flag the timeout and resume the coroutine
409
    timeout_flags[co] = true
78✔
410
    _resumable:push(co)
78✔
411

412
    -- clear the socket from the current queue
413
    if queue == "read" then
78✔
414
      _reading:remove(skt)
77✔
415
    elseif queue == "write" then
12✔
416
      _writing:remove(skt)
14✔
417
    else
418
      error("bad queue name; expected 'read'/'write', got: "..tostring(queue))
×
419
    end
420
  end
421

422

423
  -- Sets a socket timeout.
424
  -- Calling it as `sto_timeout()` will cancel the timeout.
425
  -- @param skt (socket) the socket on which to operate, use 'nil' to cancel the current timeout
426
  -- @param queue (string) the queue the socket is currently in: "read" or "write"
427
  -- @param use_connect_to (bool) if truthy, use the connect timeout instead of the
428
  --   read/write timeout implied by queue. Needed because connect also uses the "write"
429
  --   queue, so the queue value alone cannot distinguish connect from send operations.
430
  -- @return true
431
  function sto_timeout(skt, queue, use_connect_to)
158✔
432
    local co = coroutine_running()
4,967,604✔
433
    socket_register[co] = skt
4,967,604✔
434
    operation_register[co] = queue
4,967,604✔
435
    timeout_flags[co] = nil
4,967,604✔
436
    if skt then
4,967,604✔
437
      local to = (use_connect_to and user_timeouts_connect[skt]) or
2,483,813✔
438
                 (queue == "read" and user_timeouts_receive[skt]) or
2,483,486✔
439
                 user_timeouts_send[skt]
15,215✔
440
      copas.timeout(to, socket_callback)
3,394,302✔
441
    else
442
      copas.timeout(0)
2,483,802✔
443
    end
444
    return true
4,967,604✔
445
  end
446

447

448
  -- Changes the timeout to a different queue (read/write).
449
  -- Only usefull with ssl-handshakes and "wantread", "wantwrite" errors, when
450
  -- the queue has to be changed, so the timeout handler knows where to find the socket.
451
  -- @param queue (string) the new queue the socket is in, must be either "read" or "write"
452
  -- @return true
453
  function sto_change_queue(queue)
158✔
454
    operation_register[coroutine_running()] = queue
1,074✔
455
    return true
1,074✔
456
  end
457

458

459
  -- Responds with `true` if the operation timed-out.
460
  function sto_timed_out()
158✔
461
    return timeout_flags[coroutine_running()]
1,380✔
462
  end
463

464

465
  -- Returns the proper timeout error
466
  function sto_error(err)
158✔
467
    return useSocketTimeoutErrors[coroutine_running()] and err or "timeout"
78✔
468
  end
469

470
  -- only in case of testing export some internals
471
  if _G._TEST then
188✔
472
    copas._socket_register = socket_register
6✔
473
    copas._operation_register = operation_register
6✔
474
    copas._timeout_flags = timeout_flags
6✔
475
  end
476
end
477

478

479

480
-------------------------------------------------------------------------------
481
-- Coroutine based socket I/O functions.
482
-------------------------------------------------------------------------------
483

484
-- Returns "tcp"" for plain TCP and "ssl" for ssl-wrapped sockets, so truthy
485
-- for tcp based, and falsy for udp based.
486
local isTCP do
188✔
487
  local lookup = {
188✔
488
    tcp = "tcp",
158✔
489
    SSL = "ssl",
158✔
490
  }
491

492
  function isTCP(socket)
158✔
493
    return lookup[tostring(socket):sub(1,3)]
756✔
494
  end
495
end
496

497
function copas.close(skt, ...)
188✔
498
  _closed[#_closed+1] = skt
222✔
499
  return skt:close(...)
222✔
500
end
501

502

503

504
-- nil or negative is indefinitly
505
function copas.settimeout(skt, timeout)
188✔
506
  timeout = timeout or -1
216✔
507
  if type(timeout) ~= "number" then
216✔
508
    return nil, "timeout must be 'nil' or a number"
18✔
509
  end
510

511
  return copas.settimeouts(skt, timeout, timeout, timeout)
198✔
512
end
513

514
-- negative is indefinitly, nil means do not change
515
function copas.settimeouts(skt, connect, send, read)
188✔
516

517
  if connect ~= nil and type(connect) ~= "number" then
432✔
518
    return nil, "connect timeout must be 'nil' or a number"
×
519
  end
520
  if connect then
432✔
521
    if connect < 0 then
432✔
522
      connect = nil
×
523
    end
524
    user_timeouts_connect[skt] = connect
432✔
525
  end
526

527

528
  if send ~= nil and type(send) ~= "number" then
432✔
529
    return nil, "send timeout must be 'nil' or a number"
×
530
  end
531
  if send then
432✔
532
    if send < 0 then
432✔
533
      send = nil
×
534
    end
535
    user_timeouts_send[skt] = send
432✔
536
  end
537

538

539
  if read ~= nil and type(read) ~= "number" then
432✔
540
    return nil, "read timeout must be 'nil' or a number"
×
541
  end
542
  if read then
432✔
543
    if read < 0 then
432✔
544
      read = nil
×
545
    end
546
    user_timeouts_receive[skt] = read
432✔
547
  end
548

549

550
  return true
432✔
551
end
552

553
-- reads a pattern from a client and yields to the reading set on timeouts
554
-- UDP: a UDP socket expects a second argument to be a number, so it MUST
555
-- be provided as the 'pattern' below defaults to a string. Will throw a
556
-- 'bad argument' error if omitted.
557
function copas.receive(client, pattern, part)
188✔
558
  local s, err
559
  pattern = pattern or "*l"
2,468,233✔
560
  local current_log = _reading_log
2,468,233✔
561
  sto_timeout(client, "read")
2,468,233✔
562

563
  repeat
564
    s, err, part = client:receive(pattern, part)
2,468,935✔
565

566
    -- guarantees that high throughput doesn't take other threads to starvation
567
    if (math.random(100) > 90) then
2,468,935✔
568
      copas.pause()
246,779✔
569
    end
570

571
    if s then
2,468,935✔
572
      current_log[client] = nil
2,468,125✔
573
      sto_timeout()
2,468,125✔
574
      return s, err, part
2,468,125✔
575

576
    elseif not _isSocketTimeout[err] then
810✔
577
      current_log[client] = nil
48✔
578
      sto_timeout()
48✔
579
      return s, err, part
48✔
580

581
    elseif sto_timed_out() then
917✔
582
      current_log[client] = nil
60✔
583
      sto_timeout()
60✔
584
      return nil, sto_error(err), part
70✔
585
    end
586

587
    if err == "wantwrite" then -- wantwrite may be returned during SSL renegotiations
702✔
588
      current_log = _writing_log
×
589
      current_log[client] = gettime()
×
590
      sto_change_queue("write")
×
591
      coroutine_yield(client, _writing)
×
592
    else
593
      current_log = _reading_log
702✔
594
      current_log[client] = gettime()
702✔
595
      sto_change_queue("read")
702✔
596
      coroutine_yield(client, _reading)
702✔
597
    end
598
  until false
702✔
599
end
600

601
-- receives data from a client over UDP. Not available for TCP.
602
-- (this is a copy of receive() method, adapted for receivefrom() use)
603
function copas.receivefrom(client, size)
188✔
604
  local s, err, port
605
  size = size or UDP_DATAGRAM_MAX
24✔
606
  sto_timeout(client, "read")
24✔
607

608
  repeat
609
    s, err, port = client:receivefrom(size) -- upon success err holds ip address
48✔
610

611
    -- garantees that high throughput doesn't take other threads to starvation
612
    if (math.random(100) > 90) then
48✔
613
      copas.pause()
5✔
614
    end
615

616
    if s then
48✔
617
      _reading_log[client] = nil
18✔
618
      sto_timeout()
18✔
619
      return s, err, port
18✔
620

621
    elseif err ~= "timeout" then
30✔
622
      _reading_log[client] = nil
×
623
      sto_timeout()
×
624
      return s, err, port
×
625

626
    elseif sto_timed_out() then
35✔
627
      _reading_log[client] = nil
6✔
628
      sto_timeout()
6✔
629
      return nil, sto_error(err), port
7✔
630
    end
631

632
    _reading_log[client] = gettime()
24✔
633
    coroutine_yield(client, _reading)
24✔
634
  until false
24✔
635
end
636

637
-- same as above but with special treatment when reading chunks,
638
-- unblocks on any data received.
639
function copas.receivepartial(client, pattern, part)
188✔
640
  local s, err
641
  pattern = pattern or "*l"
12✔
642
  local orig_size = #(part or "")
12✔
643
  local current_log = _reading_log
12✔
644
  sto_timeout(client, "read")
12✔
645

646
  repeat
647
    s, err, part = client:receive(pattern, part)
18✔
648

649
    -- guarantees that high throughput doesn't take other threads to starvation
650
    if (math.random(100) > 90) then
18✔
651
      copas.pause()
1✔
652
    end
653

654
    if s or (type(part) == "string" and #part > orig_size) then
18✔
655
      current_log[client] = nil
12✔
656
      sto_timeout()
12✔
657
      return s, err, part
12✔
658

659
    elseif not _isSocketTimeout[err] then
6✔
660
      current_log[client] = nil
×
661
      sto_timeout()
×
662
      return s, err, part
×
663

664
    elseif sto_timed_out() then
7✔
665
      current_log[client] = nil
×
666
      sto_timeout()
×
667
      return nil, sto_error(err), part
×
668
    end
669

670
    if err == "wantwrite" then
6✔
671
      current_log = _writing_log
×
672
      current_log[client] = gettime()
×
673
      sto_change_queue("write")
×
674
      coroutine_yield(client, _writing)
×
675
    else
676
      current_log = _reading_log
6✔
677
      current_log[client] = gettime()
6✔
678
      sto_change_queue("read")
6✔
679
      coroutine_yield(client, _reading)
6✔
680
    end
681
  until false
6✔
682
end
683
copas.receivePartial = copas.receivepartial  -- compat: receivePartial is deprecated
188✔
684

685
-- sends data to a client. The operation is buffered and
686
-- yields to the writing set on timeouts
687
-- Note: from and to parameters will be ignored by/for UDP sockets
688
function copas.send(client, data, from, to)
188✔
689
  local s, err
690
  from = from or 1
15,215✔
691
  local lastIndex = from - 1
15,215✔
692
  local current_log = _writing_log
15,215✔
693
  sto_timeout(client, "write")
15,215✔
694

695
  repeat
696
    s, err, lastIndex = client:send(data, lastIndex + 1, to)
15,395✔
697

698
    -- guarantees that high throughput doesn't take other threads to starvation
699
    if (math.random(100) > 90) then
15,395✔
700
      copas.pause()
1,496✔
701
    end
702

703
    if s then
15,395✔
704
      current_log[client] = nil
15,191✔
705
      sto_timeout()
15,191✔
706
      return s, err, lastIndex
15,191✔
707

708
    elseif not _isSocketTimeout[err] then
204✔
709
      current_log[client] = nil
24✔
710
      sto_timeout()
24✔
711
      return s, err, lastIndex
24✔
712

713
    elseif sto_timed_out() then
209✔
714
      current_log[client] = nil
×
715
      sto_timeout()
×
716
      return nil, sto_error(err), lastIndex
×
717
    end
718

719
    if err == "wantread" then
180✔
720
      current_log = _reading_log
×
721
      current_log[client] = gettime()
×
722
      sto_change_queue("read")
×
723
      coroutine_yield(client, _reading)
×
724
    else
725
      current_log = _writing_log
180✔
726
      current_log[client] = gettime()
180✔
727
      sto_change_queue("write")
180✔
728
      coroutine_yield(client, _writing)
180✔
729
    end
730
  until false
180✔
731
end
732

733
function copas.sendto(client, data, ip, port)
188✔
734
  -- deprecated; for backward compatibility only, since UDP doesn't block on sending
735
  return client:sendto(data, ip, port)
×
736
end
737

738
-- waits until connection is completed
739
function copas.connect(skt, host, port)
188✔
740
  skt:settimeout(0)
212✔
741
  local ret, err, tried_more_than_once
742
  sto_timeout(skt, "write", true)
210✔
743

744
  repeat
745
    ret, err = skt:connect(host, port)
422✔
746

747
    -- non-blocking connect on Windows results in error "Operation already
748
    -- in progress" to indicate that it is completing the request async. So essentially
749
    -- it is the same as "timeout"
750
    if ret or (err ~= "timeout" and err ~= "Operation already in progress") then
414✔
751
      _writing_log[skt] = nil
198✔
752
      sto_timeout()
198✔
753
      -- Once the async connect completes, Windows returns the error "already connected"
754
      -- to indicate it is done, so that error should be ignored. Except when it is the
755
      -- first call to connect, then it was already connected to something else and the
756
      -- error should be returned
757
      if (not ret) and (err == "already connected" and tried_more_than_once) then
198✔
758
        return 1
×
759
      end
760
      return ret, err
198✔
761

762
    elseif sto_timed_out() then
252✔
763
      _writing_log[skt] = nil
12✔
764
      sto_timeout()
12✔
765
      return nil, sto_error(err)
14✔
766
    end
767

768
    tried_more_than_once = tried_more_than_once or true
204✔
769
    _writing_log[skt] = gettime()
204✔
770
    coroutine_yield(skt, _writing)
204✔
771
  until false
204✔
772
end
773

774

775
-- Wraps a tcp socket in an ssl socket and configures it. If the socket was
776
-- already wrapped, it does nothing and returns the socket.
777
-- @param wrap_params the parameters for the ssl-context
778
-- @return wrapped socket, or throws an error
779
local function ssl_wrap(skt, wrap_params)
780
  if isTCP(skt) == "ssl" then return skt end -- was already wrapped
224✔
781
  if not wrap_params then
108✔
782
    error("cannot wrap socket into a secure socket (using 'ssl.wrap()') without parameters/context")
×
783
  end
784

785
  ssl = ssl or require("ssl")
108✔
786
  local nskt = assert(ssl.wrap(skt, wrap_params)) -- assert, because we do not want to silently ignore this one!!
126✔
787

788
  nskt:settimeout(0)  -- non-blocking on the ssl-socket
108✔
789
  copas.settimeouts(nskt, user_timeouts_connect[skt],
216✔
790
    user_timeouts_send[skt], user_timeouts_receive[skt]) -- copy copas user-timeout to newly wrapped one
112✔
791

792
  local co = _autoclose_r[skt]
108✔
793
  if co then
108✔
794
    -- socket registered for autoclose, move registration to wrapped one
795
    _autoclose[co] = nskt
24✔
796
    _autoclose_r[skt] = nil
24✔
797
    _autoclose_r[nskt] = co
24✔
798
  end
799

800
  local sock_name = object_names[skt]
108✔
801
  if sock_name ~= tostring(skt) then
108✔
802
    -- socket had a custom name, so copy it over
803
    object_names[nskt] = sock_name
36✔
804
  end
805
  return nskt
108✔
806
end
807

808

809
-- For each luasec method we have a subtable, allows for future extension.
810
-- Required structure:
811
-- {
812
--   wrap = ... -- parameter to 'wrap()'; the ssl parameter table, or the context object
813
--   sni = {                  -- parameters to 'sni()'
814
--     names = string | table -- 1st parameter
815
--     strict = bool          -- 2nd parameter
816
--   }
817
-- }
818
local function normalize_sslt(sslt)
819
  local t = type(sslt)
336✔
820
  local r = setmetatable({}, {
672✔
821
    __index = function(self, key)
822
      -- a bug if this happens, here as a sanity check, just being careful since
823
      -- this is security stuff
824
      error("accessing unknown 'ssl_params' table key: "..tostring(key))
×
825
    end,
826
  })
827
  if t == "nil" then
336✔
828
    r.wrap = false
228✔
829
    r.sni = false
228✔
830

831
  elseif t == "table" then
108✔
832
    if sslt.mode or sslt.protocol then
108✔
833
      -- has the mandatory fields for the ssl-params table for handshake
834
      -- backward compatibility
835
      r.wrap = sslt
24✔
836
      r.sni = false
24✔
837
    else
838
      -- has the target definition, copy our known keys
839
      r.wrap = sslt.wrap or false -- 'or false' because we do not want nils
84✔
840
      r.sni = sslt.sni or false -- 'or false' because we do not want nils
84✔
841
    end
842

843
  elseif t == "userdata" then
×
844
    -- it's an ssl-context object for the handshake
845
    -- backward compatibility
846
    r.wrap = sslt
×
847
    r.sni = false
×
848

849
  else
850
    error("ssl parameters; did not expect type "..tostring(sslt))
×
851
  end
852

853
  return r
336✔
854
end
855

856

857
---
858
-- Peforms an (async) ssl handshake on a connected TCP client socket.
859
-- NOTE: if not ssl-wrapped already, then replace all previous socket references, with the returned new ssl wrapped socket
860
-- Throws error and does not return nil+error, as that might silently fail
861
-- in code like this;
862
--   copas.addserver(s1, function(skt)
863
--       skt = copas.wrap(skt, sparams)
864
--       skt:dohandshake()   --> without explicit error checking, this fails silently and
865
--       skt:send(body)      --> continues unencrypted
866
-- @param skt Regular LuaSocket CLIENT socket object
867
-- @param wrap_params Table with ssl parameters
868
-- @return wrapped ssl socket, or throws an error
869
function copas.dohandshake(skt, wrap_params)
188✔
870
  ssl = ssl or require("ssl")
108✔
871

872
  local nskt = ssl_wrap(skt, wrap_params)
108✔
873

874
  sto_timeout(nskt, "write", true)
108✔
875
  local queue
876

877
  repeat
878
    local success, err = nskt:dohandshake()
294✔
879

880
    if success then
294✔
881
      sto_timeout()
96✔
882
      return nskt
96✔
883

884
    elseif not _isSocketTimeout[err] then
198✔
885
      sto_timeout()
12✔
886
      error("TLS/SSL handshake failed: " .. tostring(err))
12✔
887

888
    elseif sto_timed_out() then
217✔
889
      sto_timeout()
×
890
      return nil, sto_error(err)
×
891

892
    elseif err == "wantwrite" then
186✔
893
      sto_change_queue("write")
×
894
      queue = _writing
×
895

896
    elseif err == "wantread" then
186✔
897
      sto_change_queue("read")
186✔
898
      queue = _reading
186✔
899

900
    else
901
      error("TLS/SSL handshake failed: " .. tostring(err))
×
902
    end
903

904
    coroutine_yield(nskt, queue)
186✔
905
  until false
186✔
906
end
907

908
-- flushes a client write buffer (deprecated)
909
function copas.flush()
188✔
910
end
911

912
-- wraps a TCP socket to use Copas methods (send, receive, flush and settimeout)
913
local _skt_mt_tcp = {
188✔
914
      __tostring = function(self)
915
        return tostring(self.socket).." (copas wrapped)"
18✔
916
      end,
917

918
      __index = {
188✔
919
        send = function (self, data, from, to)
920
          return copas.send (self.socket, data, from, to)
15,209✔
921
        end,
922

923
        receive = function (self, pattern, prefix)
924
          if user_timeouts_receive[self.socket] == 0 then
2,468,228✔
925
            return copas.receivepartial(self.socket, pattern, prefix)
12✔
926
          end
927
          return copas.receive(self.socket, pattern, prefix)
2,468,215✔
928
        end,
929

930
        receivepartial = function (self, pattern, prefix)
931
          return copas.receivepartial(self.socket, pattern, prefix)
×
932
        end,
933

934
        flush = function (self)
935
          return copas.flush(self.socket)
×
936
        end,
937

938
        settimeout = function (self, time)
939
          return copas.settimeout(self.socket, time)
198✔
940
        end,
941

942
        settimeouts = function (self, connect, send, receive)
943
          return copas.settimeouts(self.socket, connect, send, receive)
×
944
        end,
945

946
        -- TODO: socket.connect is a shortcut, and must be provided with an alternative
947
        -- if ssl parameters are available, it will also include a handshake
948
        connect = function(self, ...)
949
          local res, err = copas.connect(self.socket, ...)
210✔
950
          if res then
210✔
951
            if self.ssl_params.sni then self:sni() end
192✔
952
            if self.ssl_params.wrap then res, err = self:dohandshake() end
205✔
953
          end
954
          return res, err
204✔
955
        end,
956

957
        close = function(self, ...)
958
          return copas.close(self.socket, ...)
222✔
959
        end,
960

961
        -- TODO: socket.bind is a shortcut, and must be provided with an alternative
962
        bind = function(self, ...) return self.socket:bind(...) end,
188✔
963

964
        -- TODO: is this DNS related? hence blocking?
965
        getsockname = function(self, ...)
966
          local ok, ip, port, family = pcall(self.socket.getsockname, self.socket, ...)
×
967
          if ok then
×
968
            return ip, port, family
×
969
          else
970
            return nil, "not implemented by LuaSec"
×
971
          end
972
        end,
973

974
        getstats = function(self, ...) return self.socket:getstats(...) end,
188✔
975

976
        setstats = function(self, ...) return self.socket:setstats(...) end,
188✔
977

978
        listen = function(self, ...) return self.socket:listen(...) end,
188✔
979

980
        accept = function(self, ...) return self.socket:accept(...) end,
188✔
981

982
        setoption = function(self, ...)
983
          local ok, res, err = pcall(self.socket.setoption, self.socket, ...)
×
984
          if ok then
×
985
            return res, err
×
986
          else
987
            return nil, "not implemented by LuaSec"
×
988
          end
989
        end,
990

991
        getoption = function(self, ...)
992
          local ok, val, err = pcall(self.socket.getoption, self.socket, ...)
×
993
          if ok then
×
994
            return val, err
×
995
          else
996
            return nil, "not implemented by LuaSec"
×
997
          end
998
        end,
999

1000
        -- TODO: is this DNS related? hence blocking?
1001
        getpeername = function(self, ...)
1002
          local ok, ip, port, family = pcall(self.socket.getpeername, self.socket, ...)
×
1003
          if ok then
×
1004
            return ip, port, family
×
1005
          else
1006
            return nil, "not implemented by LuaSec"
×
1007
          end
1008
        end,
1009

1010
        shutdown = function(self, ...) return self.socket:shutdown(...) end,
188✔
1011

1012
        sni = function(self, names, strict)
1013
          local sslp = self.ssl_params
84✔
1014
          self.socket = ssl_wrap(self.socket, sslp.wrap)
98✔
1015
          if names == nil then
84✔
1016
            names = sslp.sni.names
72✔
1017
            strict = sslp.sni.strict
72✔
1018
          end
1019
          return self.socket:sni(names, strict)
84✔
1020
        end,
1021

1022
        dohandshake = function(self, wrap_params)
1023
          local nskt, err = copas.dohandshake(self.socket, wrap_params or self.ssl_params.wrap)
108✔
1024
          if not nskt then return nskt, err end
96✔
1025
          self.socket = nskt  -- replace internal socket with the newly wrapped ssl one
96✔
1026
          return self
96✔
1027
        end,
1028

1029
        getalpn = function(self, ...)
1030
          local ok, proto, err = pcall(self.socket.getalpn, self.socket, ...)
×
1031
          if ok then
×
1032
            return proto, err
×
1033
          else
1034
            return nil, "not a tls socket"
×
1035
          end
1036
        end,
1037

1038
        getsniname = function(self, ...)
1039
          local ok, name, err = pcall(self.socket.getsniname, self.socket, ...)
×
1040
          if ok then
×
1041
            return name, err
×
1042
          else
1043
            return nil, "not a tls socket"
×
1044
          end
1045
        end,
1046
      }
188✔
1047
}
1048

1049
-- wraps a UDP socket, copy of TCP one adapted for UDP.
1050
local _skt_mt_udp = {__index = { }}
188✔
1051
for k,v in pairs(_skt_mt_tcp) do _skt_mt_udp[k] = _skt_mt_udp[k] or v end
564✔
1052
for k,v in pairs(_skt_mt_tcp.__index) do _skt_mt_udp.__index[k] = v end
4,324✔
1053

1054
_skt_mt_udp.__index.send        = function(self, ...) return self.socket:send(...) end
194✔
1055

1056
_skt_mt_udp.__index.sendto      = function(self, ...) return self.socket:sendto(...) end
206✔
1057

1058

1059
_skt_mt_udp.__index.receive =     function (self, size)
188✔
1060
                                    return copas.receive (self.socket, (size or UDP_DATAGRAM_MAX))
12✔
1061
                                  end
1062

1063
_skt_mt_udp.__index.receivefrom = function (self, size)
188✔
1064
                                    return copas.receivefrom (self.socket, (size or UDP_DATAGRAM_MAX))
24✔
1065
                                  end
1066

1067
                                  -- TODO: is this DNS related? hence blocking?
1068
_skt_mt_udp.__index.setpeername = function(self, ...) return self.socket:setpeername(...) end
194✔
1069

1070
_skt_mt_udp.__index.setsockname = function(self, ...) return self.socket:setsockname(...) end
188✔
1071

1072
                                    -- do not close client, as it is also the server for udp.
1073
_skt_mt_udp.__index.close       = function(self, ...) return true end
200✔
1074

1075
_skt_mt_udp.__index.settimeouts = function (self, connect, send, receive)
188✔
1076
                                    return copas.settimeouts(self.socket, connect, send, receive)
×
1077
                                  end
1078

1079

1080

1081
---
1082
-- Wraps a LuaSocket socket object in an async Copas based socket object.
1083
-- @param skt The socket to wrap
1084
-- @sslt (optional) Table with ssl parameters, use an empty table to use ssl with defaults
1085
-- @return wrapped socket object
1086
function copas.wrap (skt, sslt)
188✔
1087
  if (getmetatable(skt) == _skt_mt_tcp) or (getmetatable(skt) == _skt_mt_udp) then
360✔
1088
    return skt -- already wrapped
×
1089
  end
1090

1091
  skt:settimeout(0)
362✔
1092

1093
  if isTCP(skt) then
420✔
1094
    return setmetatable ({socket = skt, ssl_params = normalize_sslt(sslt)}, _skt_mt_tcp)
392✔
1095
  else
1096
    return setmetatable ({socket = skt}, _skt_mt_udp)
24✔
1097
  end
1098
end
1099

1100
--- Wraps a handler in a function that deals with wrapping the socket and doing the
1101
-- optional ssl handshake.
1102
function copas.handler(handler, sslparams)
188✔
1103
  -- TODO: pass a timeout value to set, and use during handshake
1104
  return function (skt, ...)
1105
    skt = copas.wrap(skt, sslparams) -- this call will normalize the sslparams table
112✔
1106
    local sslp = skt.ssl_params
96✔
1107
    if sslp.sni then skt:sni(sslp.sni.names, sslp.sni.strict) end
96✔
1108
    if sslp.wrap then skt:dohandshake(sslp.wrap) end
96✔
1109
    return handler(skt, ...)
90✔
1110
  end
1111
end
1112

1113

1114
--------------------------------------------------
1115
-- Error handling
1116
--------------------------------------------------
1117

1118
local _errhandlers = setmetatable({}, { __mode = "k" })   -- error handler per coroutine
188✔
1119

1120

1121
function copas.gettraceback(msg, co, skt)
188✔
1122
  local co_str = co == nil and "nil" or copas.getthreadname(co)
38✔
1123
  local skt_str = skt == nil and "nil" or copas.getsocketname(skt)
38✔
1124
  local msg_str = msg == nil and "" or tostring(msg)
38✔
1125
  if msg_str == "" then
38✔
1126
    msg_str = ("(coroutine: %s, socket: %s)"):format(msg_str, co_str, skt_str)
×
1127
  else
1128
    msg_str = ("%s (coroutine: %s, socket: %s)"):format(msg_str, co_str, skt_str)
38✔
1129
  end
1130

1131
  if type(co) == "thread" then
38✔
1132
    -- regular Copas coroutine
1133
    return debug.traceback(co, msg_str)
38✔
1134
  end
1135
  -- not a coroutine, but the main thread, this happens if a timeout callback
1136
  -- (see `copas.timeout` causes an error (those callbacks run on the main thread).
1137
  return debug.traceback(msg_str, 2)
×
1138
end
1139

1140

1141
local function _deferror(msg, co, skt)
1142
  print(copas.gettraceback(msg, co, skt))
29✔
1143
end
1144

1145

1146
function copas.seterrorhandler(err, default)
188✔
1147
  assert(err == nil or type(err) == "function", "Expected the handler to be a function, or nil")
60✔
1148
  if default then
60✔
1149
    assert(err ~= nil, "Expected the handler to be a function when setting the default")
42✔
1150
    _deferror = err
42✔
1151
  else
1152
    _errhandlers[coroutine_running()] = err
18✔
1153
  end
1154
end
1155
copas.setErrorHandler = copas.seterrorhandler  -- deprecated; old casing
188✔
1156

1157

1158
function copas.geterrorhandler(co)
188✔
1159
  co = co or coroutine_running()
12✔
1160
  return _errhandlers[co] or _deferror
12✔
1161
end
1162

1163

1164
-- if `bool` is truthy, then the original socket errors will be returned in case of timeouts;
1165
-- `timeout, wantread, wantwrite, Operation already in progress`. If falsy, it will always
1166
-- return `timeout`.
1167
function copas.useSocketTimeoutErrors(bool)
188✔
1168
  useSocketTimeoutErrors[coroutine_running()] = not not bool -- force to a boolean
6✔
1169
end
1170

1171
-------------------------------------------------------------------------------
1172
-- Thread handling
1173
-------------------------------------------------------------------------------
1174

1175
local function _doTick (co, skt, ...)
1176
  if not co then return end
283,868✔
1177

1178
  -- if a coroutine was canceled/removed, don't resume it
1179
  if _canceled[co] then
283,868✔
1180
    _canceled[co] = nil -- also clean up the registry
24✔
1181
    _threads[co] = nil
24✔
1182
    return
24✔
1183
  end
1184

1185
  -- res: the socket (being read/write on) or the time to sleep
1186
  -- new_q: either _writing, _reading, or _sleeping
1187
  -- local time_before = gettime()
1188
  local ok, res, new_q = coroutine_resume(co, skt, ...)
283,844✔
1189
  -- local duration = gettime() - time_before
1190
  -- if duration > 1 then
1191
  --   duration = math.floor(duration * 1000)
1192
  --   pcall(_errhandlers[co] or _deferror, "task ran for "..tostring(duration).." milliseconds.", co, skt)
1193
  -- end
1194

1195
  if new_q == _reading or new_q == _writing or new_q == _sleeping then
283,838✔
1196
    -- we're yielding to a new queue
1197
    new_q:insert (res)
278,622✔
1198
    new_q:push (res, co)
278,622✔
1199
    return
278,622✔
1200
  end
1201

1202
  -- coroutine is terminating
1203

1204
  if ok and coroutine_status(co) ~= "dead" then
5,216✔
1205
    -- it called coroutine.yield from a non-Copas function which is unexpected
1206
    ok = false
6✔
1207
    res = "coroutine.yield was called without a resume first, user-code cannot yield to Copas"
6✔
1208
  end
1209

1210
  if not ok then
5,216✔
1211
    local k, e = pcall(_errhandlers[co] or _deferror, res, co, skt)
46✔
1212
    if not k then
46✔
1213
      print("Failed executing error handler: " .. tostring(e))
×
1214
    end
1215
  end
1216

1217
  local skt_to_close = _autoclose[co]
5,216✔
1218
  if skt_to_close then
5,216✔
1219
    skt_to_close:close()
120✔
1220
    _autoclose[co] = nil
120✔
1221
    _autoclose_r[skt_to_close] = nil
120✔
1222
  end
1223

1224
  _errhandlers[co] = nil
5,216✔
1225
end
1226

1227

1228
local _accept do
188✔
1229
  local client_counters = setmetatable({}, { __mode = "k" })
188✔
1230

1231
  -- accepts a connection on socket input
1232
  function _accept(server_skt, handler)
158✔
1233
    local client_skt = server_skt:accept()
126✔
1234
    if client_skt then
126✔
1235
      local count = (client_counters[server_skt] or 0) + 1
126✔
1236
      client_counters[server_skt] = count
126✔
1237
      object_names[client_skt] = object_names[server_skt] .. ":client_" .. count
140✔
1238

1239
      client_skt:settimeout(0)
126✔
1240
      copas.settimeouts(client_skt, user_timeouts_connect[server_skt],  -- copy server socket timeout settings
252✔
1241
        user_timeouts_send[server_skt], user_timeouts_receive[server_skt])
140✔
1242

1243
      local co = coroutine_create(handler)
126✔
1244
      object_names[co] = object_names[server_skt] .. ":handler_" .. count
126✔
1245

1246
      if copas.autoclose then
126✔
1247
        _autoclose[co] = client_skt
126✔
1248
        _autoclose_r[client_skt] = co
126✔
1249
      end
1250

1251
      _doTick(co, client_skt)
126✔
1252
    end
1253
  end
1254
end
1255

1256
-------------------------------------------------------------------------------
1257
-- Adds a server/handler pair to Copas dispatcher
1258
-------------------------------------------------------------------------------
1259

1260
do
1261
  local function addTCPserver(server, handler, timeout, name)
1262
    server:settimeout(0)
96✔
1263
    if name then
96✔
1264
      object_names[server] = name
×
1265
    end
1266
    _servers[server] = handler
96✔
1267
    _reading:insert(server)
96✔
1268
    if timeout then
96✔
1269
      copas.settimeout(server, timeout)
18✔
1270
    end
1271
  end
1272

1273
  local function addUDPserver(server, handler, timeout, name)
1274
    server:settimeout(0)
×
1275
    local co = coroutine_create(handler)
×
1276
    if name then
×
1277
      object_names[server] = name
×
1278
    end
1279
    object_names[co] = object_names[server]..":handler"
×
1280
    _reading:insert(server)
×
1281
    if timeout then
×
1282
      copas.settimeout(server, timeout)
×
1283
    end
1284
    _doTick(co, server)
×
1285
  end
1286

1287

1288
  function copas.addserver(server, handler, timeout, name)
188✔
1289
    if isTCP(server) then
112✔
1290
      addTCPserver(server, handler, timeout, name)
112✔
1291
    else
1292
      addUDPserver(server, handler, timeout, name)
×
1293
    end
1294
  end
1295
end
1296

1297

1298
function copas.removeserver(server, keep_open)
188✔
1299
  local skt = server
90✔
1300
  local mt = getmetatable(server)
90✔
1301
  if mt == _skt_mt_tcp or mt == _skt_mt_udp then
90✔
1302
    skt = server.socket
×
1303
  end
1304

1305
  _servers:remove(skt)
90✔
1306
  _reading:remove(skt)
90✔
1307

1308
  if keep_open then
90✔
1309
    return true
18✔
1310
  end
1311
  return server:close()
72✔
1312
end
1313

1314

1315

1316
-------------------------------------------------------------------------------
1317
-- Adds an new coroutine thread to Copas dispatcher
1318
-------------------------------------------------------------------------------
1319
function copas.addnamedthread(name, handler, ...)
188✔
1320
  if type(name) == "function" and type(handler) == "string" then
5,344✔
1321
    -- old call, flip args for compatibility
1322
    name, handler = handler, name
×
1323
  end
1324

1325
  -- create a coroutine that skips the first argument, which is always the socket
1326
  -- passed by the scheduler, but `nil` in case of a task/thread
1327
  local thread = coroutine_create(function(_, ...)
10,688✔
1328
    copas.pause()
5,344✔
1329
    return handler(...)
5,326✔
1330
  end)
1331
  if name then
5,344✔
1332
    object_names[thread] = name
460✔
1333
  end
1334

1335
  _threads[thread] = true -- register this thread so it can be removed
5,344✔
1336
  _doTick (thread, nil, ...)
5,344✔
1337
  return thread
5,344✔
1338
end
1339

1340

1341
function copas.addthread(handler, ...)
188✔
1342
  return copas.addnamedthread(nil, handler, ...)
4,818✔
1343
end
1344

1345

1346
function copas.removethread(thread)
188✔
1347
  -- if the specified coroutine is registered, add it to the canceled table so
1348
  -- that next time it tries to resume it exits.
1349
  _canceled[thread] = _threads[thread or 0]
54✔
1350
  _sleeping:cancel(thread)
54✔
1351
end
1352

1353

1354

1355
-------------------------------------------------------------------------------
1356
-- Sleep/pause management functions
1357
-------------------------------------------------------------------------------
1358

1359
-- yields the current coroutine and wakes it after 'sleeptime' seconds.
1360
-- If sleeptime < 0 then it sleeps until explicitly woken up using 'wakeup'
1361
-- TODO: deprecated, remove in next major
1362
function copas.sleep(sleeptime)
188✔
1363
  coroutine_yield((sleeptime or 0), _sleeping)
×
1364
end
1365

1366

1367
-- yields the current coroutine and wakes it after 'sleeptime' seconds.
1368
-- if sleeptime < 0 then it sleeps 0 seconds.
1369
function copas.pause(sleeptime)
188✔
1370
  local s = gettime()
274,098✔
1371
  if sleeptime and sleeptime > 0 then
274,098✔
1372
    coroutine_yield(sleeptime, _sleeping)
8,432✔
1373
  else
1374
    coroutine_yield(0, _sleeping)
266,846✔
1375
  end
1376
  return gettime() - s
273,868✔
1377
end
1378

1379

1380
-- yields the current coroutine until explicitly woken up using 'wakeup'
1381
function copas.pauseforever()
188✔
1382
  local s = gettime()
3,222✔
1383
  coroutine_yield(-1, _sleeping)
3,222✔
1384
  return gettime() - s
3,204✔
1385
end
1386

1387

1388
-- Wakes up a sleeping coroutine 'co'.
1389
function copas.wakeup(co)
188✔
1390
  _sleeping:wakeup(co)
3,234✔
1391
end
1392

1393

1394

1395
-------------------------------------------------------------------------------
1396
-- Timeout management
1397
-------------------------------------------------------------------------------
1398

1399
do
1400
  local timeout_register = setmetatable({}, { __mode = "k" })
188✔
1401
  local timerwheel = require("timerwheel").new({
377✔
1402
      now = gettime,
188✔
1403
      precision = TIMEOUT_PRECISION,
188✔
1404
      ringsize = math.floor(60*60*24/TIMEOUT_PRECISION),  -- ring size 1 day
188✔
1405
      err_handler = function(err)
1406
        return _deferror(err, core_timer_thread)
16✔
1407
      end,
1408
    })
1409

1410
  core_timer_thread = copas.addnamedthread("copas_core_timer", function()
376✔
1411
    while true do
1412
      copas.pause(TIMEOUT_PRECISION)
6,342✔
1413
      timerwheel:step()
7,193✔
1414
    end
1415
  end)
1416

1417
  -- get the number of timeouts running
1418
  function copas.gettimeouts()
188✔
1419
    return timerwheel:count()
2,698✔
1420
  end
1421

1422
  --- Sets the timeout for the current coroutine.
1423
  -- @param delay delay (seconds), use 0 (or math.huge) to cancel the timerout
1424
  -- @param callback function with signature: `function(coroutine)` where coroutine is the routine that timed-out
1425
  -- @return true
1426
  function copas.timeout(delay, callback)
188✔
1427
    local co = coroutine_running()
4,972,504✔
1428
    local existing_timer = timeout_register[co]
4,972,504✔
1429

1430
    if existing_timer then
4,972,504✔
1431
      timerwheel:cancel(existing_timer)
4,422✔
1432
    end
1433

1434
    if delay > 0 and delay ~= math.huge then
4,972,504✔
1435
      timeout_register[co] = timerwheel:set(delay, callback, co)
6,962✔
1436
    elseif delay == 0 or delay == math.huge then
4,966,542✔
1437
      timeout_register[co] = nil
4,966,542✔
1438
    else
1439
      error("timout value must be greater than or equal to 0, got: "..tostring(delay))
×
1440
    end
1441

1442
    return true
4,972,504✔
1443
  end
1444

1445
end
1446

1447

1448
-------------------------------------------------------------------------------
1449
-- main tasks: manage readable and writable socket sets
1450
-------------------------------------------------------------------------------
1451
-- a task is an object with a required method `step()` that deals with a
1452
-- single step for that task.
1453

1454
local _tasks = {} do
188✔
1455
  function _tasks:add(tsk)
188✔
1456
    _tasks[#_tasks + 1] = tsk
752✔
1457
  end
1458
end
1459

1460

1461
-- a task to check ready to read events
1462
local _readable_task = {} do
188✔
1463

1464
  _readable_task._events = {}
188✔
1465

1466
  local function tick(skt)
1467
    local handler = _servers[skt]
978✔
1468
    if handler then
978✔
1469
      _accept(skt, handler)
147✔
1470
    else
1471
      _reading:remove(skt)
852✔
1472
      _doTick(_reading:pop(skt), skt)
1,022✔
1473
    end
1474
  end
1475

1476
  function _readable_task:step()
188✔
1477
    for _, skt in ipairs(self._events) do
268,915✔
1478
      tick(skt)
978✔
1479
    end
1480
  end
1481

1482
  _tasks:add(_readable_task)
218✔
1483
end
1484

1485

1486
-- a task to check ready to write events
1487
local _writable_task = {} do
188✔
1488

1489
  _writable_task._events = {}
188✔
1490

1491
  local function tick(skt)
1492
    _writing:remove(skt)
372✔
1493
    _doTick(_writing:pop(skt), skt)
433✔
1494
  end
1495

1496
  function _writable_task:step()
188✔
1497
    for _, skt in ipairs(self._events) do
268,304✔
1498
      tick(skt)
372✔
1499
    end
1500
  end
1501

1502
  _tasks:add(_writable_task)
218✔
1503
end
1504

1505

1506

1507
-- sleeping threads task
1508
local _sleeping_task = {} do
188✔
1509

1510
  function _sleeping_task:step()
188✔
1511
    local now = gettime()
267,932✔
1512

1513
    local co = _sleeping:pop(now)
267,932✔
1514
    while co do
274,973✔
1515
      -- we're pushing them to _resumable, since that list will be replaced before
1516
      -- executing. This prevents tasks running twice in a row with pause(0) for example.
1517
      -- So here we won't execute, but at _resumable step which is next
1518
      _resumable:push(co)
7,041✔
1519
      co = _sleeping:pop(now)
8,222✔
1520
    end
1521
  end
1522

1523
  _tasks:add(_sleeping_task)
188✔
1524
end
1525

1526

1527

1528
-- resumable threads task
1529
local _resumable_task = {} do
188✔
1530

1531
  function _resumable_task:step()
188✔
1532
    -- replace the resume list before iterating, so items placed in there
1533
    -- will indeed end up in the next copas step, not in this one, and not
1534
    -- create a loop
1535
    local resumelist = _resumable:clear_resumelist()
267,932✔
1536

1537
    for _, co in ipairs(resumelist) do
545,105✔
1538
      _doTick(co)
277,174✔
1539
    end
1540
  end
1541

1542
  _tasks:add(_resumable_task)
188✔
1543
end
1544

1545

1546
-------------------------------------------------------------------------------
1547
-- Checks for reads and writes on sockets
1548
-------------------------------------------------------------------------------
1549
local _select_plain do
188✔
1550

1551
  local last_cleansing = 0
188✔
1552
  local duration = function(t2, t1) return t2-t1 end
268,038✔
1553

1554
  if not socket then
188✔
1555
    -- socket module unavailable, switch to luasystem sleep
1556
    _select_plain = block_sleep
6✔
1557
  else
1558
    -- use socket.select to handle socket-io
1559
    _select_plain = function(timeout)
1560
      local err
1561
      local now = gettime()
267,850✔
1562

1563
      -- remove any closed sockets to prevent select from hanging on them
1564
      if _closed[1] then
267,850✔
1565
        for i, skt in ipairs(_closed) do
441✔
1566
          _closed[i] = { _reading:remove(skt), _writing:remove(skt) }
296✔
1567
        end
1568
      end
1569

1570
      _readable_task._events, _writable_task._events, err = socket.select(_reading, _writing, timeout)
267,850✔
1571
      local r_events, w_events = _readable_task._events, _writable_task._events
267,850✔
1572

1573
      -- inject closed sockets in readable/writeable task so they can error out properly
1574
      if _closed[1] then
267,850✔
1575
        for i, skts in ipairs(_closed) do
441✔
1576
          _closed[i] = nil
222✔
1577
          r_events[#r_events+1] = skts[1]
222✔
1578
          w_events[#w_events+1] = skts[2]
222✔
1579
        end
1580
      end
1581

1582
      if duration(now, last_cleansing) > WATCH_DOG_TIMEOUT then
365,615✔
1583
        last_cleansing = now
176✔
1584

1585
        -- Check all sockets selected for reading, and check how long they have been waiting
1586
        -- for data already, without select returning them as readable
1587
        for skt,time in pairs(_reading_log) do
176✔
1588
          if not r_events[skt] and duration(now, time) > WATCH_DOG_TIMEOUT then
×
1589
            -- This one timedout while waiting to become readable, so move
1590
            -- it in the readable list and try and read anyway, despite not
1591
            -- having been returned by select
1592
            _reading_log[skt] = nil
×
1593
            r_events[#r_events + 1] = skt
×
1594
            r_events[skt] = #r_events
×
1595
          end
1596
        end
1597

1598
        -- Do the same for writing
1599
        for skt,time in pairs(_writing_log) do
176✔
1600
          if not w_events[skt] and duration(now, time) > WATCH_DOG_TIMEOUT then
×
1601
            _writing_log[skt] = nil
×
1602
            w_events[#w_events + 1] = skt
×
1603
            w_events[skt] = #w_events
×
1604
          end
1605
        end
1606
      end
1607

1608
      if err == "timeout" and #r_events + #w_events > 0 then
267,850✔
1609
        return nil
6✔
1610
      else
1611
        return err
267,844✔
1612
      end
1613
    end
1614
  end
1615
end
1616

1617

1618

1619
-------------------------------------------------------------------------------
1620
-- Dispatcher loop step.
1621
-- Listen to client requests and handles them
1622
-- Returns false if no socket-data was handled, or true if there was data
1623
-- handled (or nil + error message)
1624
-------------------------------------------------------------------------------
1625

1626
local copas_stats
1627
local min_ever, max_ever
1628

1629
local _select = _select_plain
188✔
1630

1631
-- instrumented version of _select() to collect stats
1632
local _select_instrumented = function(timeout)
1633
  if copas_stats then
×
1634
    local step_duration = gettime() - copas_stats.step_start
×
1635
    copas_stats.duration_max = math.max(copas_stats.duration_max, step_duration)
×
1636
    copas_stats.duration_min = math.min(copas_stats.duration_min, step_duration)
×
1637
    copas_stats.duration_tot = copas_stats.duration_tot + step_duration
×
1638
    copas_stats.steps = copas_stats.steps + 1
×
1639
  else
1640
    copas_stats = {
×
1641
      duration_max = -1,
1642
      duration_min = 999999,
1643
      duration_tot = 0,
1644
      steps = 0,
1645
    }
1646
  end
1647

1648
  local err = _select_plain(timeout)
×
1649

1650
  local now = gettime()
×
1651
  copas_stats.time_start = copas_stats.time_start or now
×
1652
  copas_stats.step_start = now
×
1653

1654
  return err
×
1655
end
1656

1657

1658
function copas.step(timeout)
188✔
1659
  -- Need to wake up the select call in time for the next sleeping event
1660
  if not _resumable:done() then
365,714✔
1661
    timeout = 0
261,967✔
1662
  else
1663
    timeout = math.min(_sleeping:getnext(), timeout or math.huge)
6,959✔
1664
  end
1665

1666
  local err = _select(timeout)
267,937✔
1667

1668
  for _, tsk in ipairs(_tasks) do
1,339,669✔
1669
    tsk:step()
1,071,738✔
1670
  end
1671

1672
  if err then
267,931✔
1673
    if err == "timeout" then
266,743✔
1674
      if timeout + 0.01 > TIMEOUT_PRECISION and math.random(100) > 90 then
266,656✔
1675
        -- we were idle, so occasionally do a GC sweep to ensure lingering
1676
        -- sockets are closed, and we don't accidentally block the loop from
1677
        -- exiting
1678
        collectgarbage()
415✔
1679
      end
1680
      return false
266,656✔
1681
    end
1682
    return nil, err
87✔
1683
  end
1684

1685
  return true
1,188✔
1686
end
1687

1688

1689
-------------------------------------------------------------------------------
1690
-- Check whether there is something to do.
1691
-- returns false if there are no sockets for read/write nor tasks scheduled
1692
-- (which means Copas is in an empty spin)
1693
-------------------------------------------------------------------------------
1694
function copas.finished()
188✔
1695
  return #_reading == 0 and #_writing == 0 and _resumable:done() and _sleeping:done(copas.gettimeouts())
269,363✔
1696
end
1697

1698

1699
local resetexit do
188✔
1700
  local exit_semaphore, exiting
1701

1702
  function resetexit()
158✔
1703
    exit_semaphore = copas.semaphore.new(1, 0, math.huge)
385✔
1704
    exiting = false
308✔
1705
  end
1706

1707
  -- Signals tasks to exit. But only if they check for it. By calling `copas.exiting`
1708
  -- they can check if they should exit. Or by calling `copas.waitforexit` they can
1709
  -- wait until the exit signal is given.
1710
  function copas.exit()
188✔
1711
    if exiting then return end
302✔
1712
    exiting = true
302✔
1713
    exit_semaphore:destroy()
302✔
1714
  end
1715

1716
  -- returns whether Copas is in the process of exiting. Exit can be started by
1717
  -- calling `copas.exit()`.
1718
  function copas.exiting()
188✔
1719
    return exiting
598✔
1720
  end
1721

1722
  -- Pauses the current coroutine until Copas is exiting. To be used as an exit
1723
  -- signal for tasks that need to clean up before exiting.
1724
  function copas.waitforexit()
188✔
1725
    exit_semaphore:take(1)
12✔
1726
  end
1727
end
1728

1729

1730
--- Forcibly cancels all pending work and signals exit.
1731
-- Intended for test teardown only. Abandons all registered threads and sockets
1732
-- without giving them a chance to clean up. After this call copas.finished()
1733
-- will return true and the loop will exit. The module is left in a clean state
1734
-- ready for the next copas.loop() call.
1735
function copas.cancelall()
188✔
1736
  -- 1. clear resumable queue
1737
  _resumable:clear_resumelist()
×
1738

1739
  -- 2. drain sleeping heap
1740
  _sleeping:cancelall()
×
1741

1742
  -- 3. close and drain reading sockets
1743
  while _reading[1] do
×
1744
    copas.close(_reading[1])
×
1745
    _reading:remove(_reading[1])
×
1746
  end
1747

1748
  -- 4. close and drain writing sockets
1749
  while _writing[1] do
×
1750
    copas.close(_writing[1])
×
1751
    _writing:remove(_writing[1])
×
1752
  end
1753

1754
  -- 5. remove all servers
1755
  while _servers[1] do
×
1756
    copas.removeserver(_servers[1])
×
1757
  end
1758

1759
  -- 6. clear non-weak ancillary tables
1760
  _closed = {}
×
1761
  _reading_log = {}
×
1762
  _writing_log = {}
×
1763

1764
  -- 7. signal exit
1765
  copas.exit()
×
1766
end
1767

1768

1769
local _getstats do
188✔
1770
  local _getstats_instrumented, _getstats_plain
1771

1772

1773
  function _getstats_plain(enable)
158✔
1774
    -- this function gets hit if turned off, so turn on if true
1775
    if enable == true then
×
1776
      _select = _select_instrumented
×
1777
      _getstats = _getstats_instrumented
×
1778
      -- reset stats
1779
      min_ever = nil
×
1780
      max_ever = nil
×
1781
      copas_stats = nil
×
1782
    end
1783
    return {}
×
1784
  end
1785

1786

1787
  -- convert from seconds to millisecs, with microsec precision
1788
  local function useconds(t)
1789
    return math.floor((t * 1000000) + 0.5) / 1000
×
1790
  end
1791
  -- convert from seconds to seconds, with millisec precision
1792
  local function mseconds(t)
1793
    return math.floor((t * 1000) + 0.5) / 1000
×
1794
  end
1795

1796

1797
  function _getstats_instrumented(enable)
158✔
1798
    if enable == false then
×
1799
      _select = _select_plain
×
1800
      _getstats = _getstats_plain
×
1801
      -- instrumentation disabled, so switch to the plain implementation
1802
      return _getstats(enable)
×
1803
    end
1804
    if (not copas_stats) or (copas_stats.step == 0) then
×
1805
      return {}
×
1806
    end
1807
    local stats = copas_stats
×
1808
    copas_stats = nil
×
1809
    min_ever = math.min(min_ever or 9999999, stats.duration_min)
×
1810
    max_ever = math.max(max_ever or 0, stats.duration_max)
×
1811
    stats.duration_min_ever = min_ever
×
1812
    stats.duration_max_ever = max_ever
×
1813
    stats.duration_avg = stats.duration_tot / stats.steps
×
1814
    stats.step_start = nil
×
1815
    stats.time_end = gettime()
×
1816
    stats.time_tot = stats.time_end - stats.time_start
×
1817
    stats.time_avg = stats.time_tot / stats.steps
×
1818

1819
    stats.duration_avg = useconds(stats.duration_avg)
×
1820
    stats.duration_max = useconds(stats.duration_max)
×
1821
    stats.duration_max_ever = useconds(stats.duration_max_ever)
×
1822
    stats.duration_min = useconds(stats.duration_min)
×
1823
    stats.duration_min_ever = useconds(stats.duration_min_ever)
×
1824
    stats.duration_tot = useconds(stats.duration_tot)
×
1825
    stats.time_avg = useconds(stats.time_avg)
×
1826
    stats.time_start = mseconds(stats.time_start)
×
1827
    stats.time_end = mseconds(stats.time_end)
×
1828
    stats.time_tot = mseconds(stats.time_tot)
×
1829
    return stats
×
1830
  end
1831

1832
  _getstats = _getstats_plain
188✔
1833
end
1834

1835

1836
function copas.status(enable_stats)
188✔
1837
  local res = _getstats(enable_stats)
×
1838
  res.running = not not copas.running
×
1839
  res.timeout = copas.gettimeouts()
×
1840
  res.timer, res.inactive = _sleeping:status()
×
1841
  res.read = #_reading
×
1842
  res.write = #_writing
×
1843
  res.active = _resumable:count()
×
1844
  return res
×
1845
end
1846

1847

1848
-------------------------------------------------------------------------------
1849
-- Dispatcher endless loop.
1850
-- Listen to client requests and handles them forever
1851
-------------------------------------------------------------------------------
1852
function copas.loop(initializer, timeout)
218✔
1853
  if type(initializer) == "function" then
308✔
1854
    copas.addnamedthread("copas_initializer", initializer)
141✔
1855
  else
1856
    timeout = initializer or timeout
186✔
1857
  end
1858

1859
  resetexit()
308✔
1860
  copas.running = true
308✔
1861
  while true do
1862
    copas.step(timeout)
267,937✔
1863
    if copas.finished() then
365,707✔
1864
      if copas.exiting() then
695✔
1865
        break
149✔
1866
      end
1867
      copas.exit()
296✔
1868
    end
1869
  end
1870
  copas.running = false
302✔
1871
end
1872

1873

1874
-------------------------------------------------------------------------------
1875
-- Naming sockets and coroutines.
1876
-------------------------------------------------------------------------------
1877
do
1878
  local function realsocket(skt)
1879
    local mt = getmetatable(skt)
90✔
1880
    if mt == _skt_mt_tcp or mt == _skt_mt_udp then
90✔
1881
      return skt.socket
90✔
1882
    else
1883
      return skt
×
1884
    end
1885
  end
1886

1887

1888
  function copas.setsocketname(name, skt)
218✔
1889
    assert(type(name) == "string", "expected arg #1 to be a string")
90✔
1890
    skt = assert(realsocket(skt), "expected arg #2 to be a socket")
105✔
1891
    object_names[skt] = name
90✔
1892
  end
1893

1894

1895
  function copas.getsocketname(skt)
218✔
1896
    skt = assert(realsocket(skt), "expected arg #1 to be a socket")
×
1897
    return object_names[skt]
×
1898
  end
1899
end
1900

1901

1902
function copas.setthreadname(name, coro)
218✔
1903
  assert(type(name) == "string", "expected arg #1 to be a string")
60✔
1904
  coro = coro or coroutine_running()
60✔
1905
  assert(type(coro) == "thread", "expected arg #2 to be a coroutine or nil")
60✔
1906
  object_names[coro] = name
60✔
1907
end
1908

1909

1910
function copas.getthreadname(coro)
218✔
1911
  coro = coro or coroutine_running()
38✔
1912
  assert(type(coro) == "thread", "expected arg #1 to be a coroutine or nil")
38✔
1913
  return object_names[coro]
40✔
1914
end
1915

1916
-------------------------------------------------------------------------------
1917
-- Debug functionality.
1918
-------------------------------------------------------------------------------
1919
do
1920
  copas.debug = {}
188✔
1921

1922
  local log_core    -- if truthy, the core-timer will also be logged
1923
  local debug_log   -- function used as logger
1924

1925

1926
  local debug_yield = function(skt, queue)
1927
    local name = object_names[coroutine_running()]
8,259✔
1928

1929
    if log_core or name ~= "copas_core_timer" then
8,259✔
1930
      if queue == _sleeping then
8,236✔
1931
        debug_log("yielding '", name, "' to SLEEP for ", skt," seconds")
8,130✔
1932

1933
      elseif queue == _writing then
106✔
1934
        debug_log("yielding '", name, "' to WRITE on '", object_names[skt], "'")
14✔
1935

1936
      elseif queue == _reading then
94✔
1937
        debug_log("yielding '", name, "' to READ on '", object_names[skt], "'")
96✔
1938

1939
      else
1940
        debug_log("thread '", name, "' yielding to unexpected queue; ", tostring(queue), " (", type(queue), ")", debug.traceback())
×
1941
      end
1942
    end
1943

1944
    return coroutine.yield(skt, queue)
8,259✔
1945
  end
1946

1947

1948
  local debug_resume = function(coro, skt, ...)
1949
    local name = object_names[coro]
8,271✔
1950

1951
    if skt then
8,271✔
1952
      debug_log("resuming '", name, "' for socket '", object_names[skt], "'")
106✔
1953
    else
1954
      if log_core or name ~= "copas_core_timer" then
8,165✔
1955
        debug_log("resuming '", name, "'")
8,142✔
1956
      end
1957
    end
1958
    return coroutine.resume(coro, skt, ...)
8,271✔
1959
  end
1960

1961

1962
  local debug_create = function(f)
1963
    local f_wrapped = function(...)
1964
      local results = pack(f(...))
14✔
1965
      debug_log("exiting '", object_names[coroutine_running()], "'")
12✔
1966
      return unpack(results)
12✔
1967
    end
1968

1969
    return coroutine.create(f_wrapped)
12✔
1970
  end
1971

1972

1973
  debug_log = fnil
188✔
1974

1975

1976
  -- enables debug output for all coroutine operations.
1977
  function copas.debug.start(logger, core)
376✔
1978
    log_core = core
6✔
1979
    debug_log = logger or print
6✔
1980
    coroutine_yield = debug_yield
6✔
1981
    coroutine_resume = debug_resume
6✔
1982
    coroutine_create = debug_create
6✔
1983
  end
1984

1985

1986
  -- disables debug output for coroutine operations.
1987
  function copas.debug.stop()
376✔
1988
    debug_log = fnil
×
1989
    coroutine_yield = coroutine.yield
×
1990
    coroutine_resume = coroutine.resume
×
1991
    coroutine_create = coroutine.create
×
1992
  end
1993

1994
  do
1995
    local call_id = 0
188✔
1996

1997
    -- Description table of socket functions for debug output.
1998
    -- each socket function name has TWO entries;
1999
    -- 'name_in' and 'name_out', each being an array of names/descriptions of respectively
2000
    -- input parameters and return values.
2001
    -- If either table has a 'callback' key, then that is a function that will be called
2002
    -- with the parameters/return-values for further inspection.
2003
    local args = {
188✔
2004
      settimeout_in = {
188✔
2005
        "socket ",
158✔
2006
        "seconds",
158✔
2007
        "mode   ",
2008
      },
188✔
2009
      settimeout_out = {
188✔
2010
        "success",
158✔
2011
        "error  ",
2012
      },
188✔
2013
      connect_in = {
188✔
2014
        "socket ",
158✔
2015
        "address",
158✔
2016
        "port   ",
2017
      },
188✔
2018
      connect_out = {
188✔
2019
        "success",
158✔
2020
        "error  ",
2021
      },
188✔
2022
      getfd_in = {
188✔
2023
        "socket ",
2024
        -- callback = function(...)
2025
        --   print(debug.traceback("called from:", 4))
2026
        -- end,
2027
      },
188✔
2028
      getfd_out = {
188✔
2029
        "fd",
2030
      },
188✔
2031
      send_in = {
188✔
2032
        "socket   ",
158✔
2033
        "data     ",
158✔
2034
        "idx-start",
158✔
2035
        "idx-end  ",
2036
      },
188✔
2037
      send_out = {
188✔
2038
        "last-idx-send    ",
158✔
2039
        "error            ",
158✔
2040
        "err-last-idx-send",
2041
      },
188✔
2042
      receive_in = {
188✔
2043
        "socket ",
158✔
2044
        "pattern",
158✔
2045
        "prefix ",
2046
      },
188✔
2047
      receive_out = {
188✔
2048
        "received    ",
158✔
2049
        "error       ",
158✔
2050
        "partial data",
2051
      },
188✔
2052
      dirty_in = {
188✔
2053
        "socket",
2054
        -- callback = function(...)
2055
        --   print(debug.traceback("called from:", 4))
2056
        -- end,
2057
      },
188✔
2058
      dirty_out = {
188✔
2059
        "data in read-buffer",
2060
      },
188✔
2061
      close_in = {
188✔
2062
        "socket",
2063
        -- callback = function(...)
2064
        --   print(debug.traceback("called from:", 4))
2065
        -- end,
2066
      },
188✔
2067
      close_out = {
188✔
2068
        "success",
158✔
2069
        "error",
2070
      },
188✔
2071
    }
2072
    local function print_call(func, msg, ...)
2073
      print(msg)
1,106✔
2074
      local arg = pack(...)
1,106✔
2075
      local desc = args[func] or {}
1,106✔
2076
      for i = 1, math.max(arg.n, #desc) do
2,356✔
2077
        local value = arg[i]
1,250✔
2078
        if type(value) == "string" then
1,250✔
2079
          local xvalue = value:sub(1,30)
36✔
2080
          if xvalue ~= value then
36✔
2081
            xvalue = xvalue .."(...truncated)"
×
2082
          end
2083
          print("\t"..(desc[i] or i)..": '"..tostring(xvalue).."' ("..type(value).." #"..#value..")")
36✔
2084
        else
2085
          print("\t"..(desc[i] or i)..": '"..tostring(value).."' ("..type(value)..")")
1,214✔
2086
        end
2087
      end
2088
      if desc.callback then
1,106✔
2089
        desc.callback(...)
×
2090
      end
2091
    end
2092

2093
    local debug_mt = {
188✔
2094
      __index = function(self, key)
2095
        local value = self.__original_socket[key]
553✔
2096
        if type(value) ~= "function" then
553✔
2097
          return value
×
2098
        end
2099
        return function(self2, ...)
2100
            local my_id = call_id + 1
553✔
2101
            call_id = my_id
553✔
2102
            local results
2103

2104
            if self2 ~= self then
553✔
2105
              -- there is no self
2106
              print_call(tostring(key).."_in", my_id .. "-calling '"..tostring(key) .. "' with; ", self, ...)
×
2107
              results = pack(value(self, ...))
×
2108
            else
2109
              print_call(tostring(key).."_in", my_id .. "-calling '" .. tostring(key) .. "' with; ", self.__original_socket, ...)
553✔
2110
              results = pack(value(self.__original_socket, ...))
845✔
2111
            end
2112
            print_call(tostring(key).."_out", my_id .. "-results '"..tostring(key) .. "' returned; ", unpack(results))
845✔
2113
            return unpack(results)
553✔
2114
          end
2115
      end,
2116
      __tostring = function(self)
2117
        return tostring(self.__original_socket)
48✔
2118
      end
2119
    }
2120

2121

2122
    -- wraps a socket (copas or luasocket) in a debug version printing all calls
2123
    -- and their parameters/return values. Extremely noisy!
2124
    -- returns the wrapped socket.
2125
    -- NOTE: only for plain sockets, will not support TLS
2126
    function copas.debug.socket(original_skt)
376✔
2127
      if (getmetatable(original_skt) == _skt_mt_tcp) or (getmetatable(original_skt) == _skt_mt_udp) then
12✔
2128
        -- already wrapped as Copas socket, so recurse with the original luasocket one
2129
        original_skt.socket = copas.debug.socket(original_skt.socket)
×
2130
        return original_skt
×
2131
      end
2132

2133
      local proxy = setmetatable({
24✔
2134
        __original_socket = original_skt
12✔
2135
      }, debug_mt)
12✔
2136

2137
      return proxy
12✔
2138
    end
2139
  end
2140
end
2141

2142

2143
return copas
188✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc