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

lunarmodules / copas / 30429780692

29 Jul 2026 06:55AM UTC coverage: 85.665%. Remained the same
30429780692

push

github

web-flow
chore(comment): fix small comment to be correct (#216)

1494 of 1744 relevant lines covered (85.67%)

53855.07 hits per line

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

81.32
/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
206✔
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
206✔
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
206✔
26
  if pcall(require, "socket") then
207✔
27
    -- found LuaSocket
28
    socket = require "socket"
200✔
29
  end
30

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

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

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

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

52

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

59

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

65

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

72

73
if socket then
206✔
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 = {
200✔
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
108✔
84
    local err = (...)
54✔
85
    if type(err) == "table" and getmetatable(err) == err_mt then
54✔
86
      return nil, err[1]
54✔
87
    else
88
      error(err)
×
89
    end
90
  end
91

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

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

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

112

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

121
  copas = setmetatable({},{
412✔
122
    __index = function(self, key)
123
      if submodules[key] then
266✔
124
        self[key] = require("copas."..key)
268✔
125
        submodules[key] = nil
266✔
126
        return rawget(self, key)
266✔
127
      end
128
    end,
129
    __call = function(self, ...)
130
      return self.loop(...)
6✔
131
    end,
132
  })
206✔
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"
206✔
138
copas._DESCRIPTION = "Coroutine Oriented Portable Asynchronous Services"
206✔
139
copas._VERSION     = "Copas 4.11.0"
206✔
140

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

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

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

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

164
-------------------------------------------------------------------------------
165
-- Simple set implementation
166
-- tracks at the waiting coroutine per socket in the set.
167
-- Sets exist for reading and writing. So each socket can have a reader and writer
168
-- simultaneously, but only one reader and one writer at a time.
169
-------------------------------------------------------------------------------
170

171
local function newsocketset()
172
  local set = {}
618✔
173

174
  do  -- set implementation
175
    local reverse = {}
618✔
176

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

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

203
  end
204

205
  do  -- single-waiter implementation
206
    -- the set instance (read or write) determines what operation the coroutine is waiting for
207
    local waiters = setmetatable({}, { __mode = "k" }) -- coroutine by socket
618✔
208

209
    -- Registers the coroutine as the socket's waiter, to be resumed
210
    -- once the socket becomes ready.
211
    -- @return true on success, or nil + error message if another coroutine
212
    -- is already waiting on this socket read/write.
213
    function set:claim(skt, co)
618✔
214
      if waiters[skt] then
1,185✔
215
        return nil, "Operation already in progress"
12✔
216
      end
217
      waiters[skt] = co
1,173✔
218
      return true
1,173✔
219
    end
220

221
    -- Clears and returns the coroutine waiting on the socket read/write operation, or nil if
222
    -- none is waiting.
223
    function set:release(skt)
618✔
224
      local co = waiters[skt]
1,173✔
225
      waiters[skt] = nil
1,173✔
226
      return co
1,173✔
227
    end
228

229
    -- Drops the socket from the set and discards its waiting coroutine (if
230
    -- any), without resuming it. Only call this when the socket is being
231
    -- discarded outright and no waiter is expected to be woken through the
232
    -- normal readiness path (e.g. the socket object itself is being thrown
233
    -- away). Do not use this as a general substitute for `remove`: if a
234
    -- waiter still needs to observe the outcome (for example a coroutine
235
    -- waiting on a socket that is being closed, which is resumed via the
236
    -- normal tick()/release() path with a "closed" result), purging here
237
    -- would silently drop it instead.
238
    function set:purge(skt)
618✔
239
      waiters[skt] = nil
×
240
      self:remove(skt)
×
241
    end
242

243
  end
244

245
  return set
618✔
246
end
247

248

249

250
-- Threads immediately resumable
251
local _resumable = {} do
206✔
252
  local resumelist = {}
206✔
253

254
  function _resumable:push(co)
206✔
255
    resumelist[#resumelist + 1] = co
217,030✔
256
  end
257

258
  function _resumable:clear_resumelist()
206✔
259
    local lst = resumelist
207,563✔
260
    resumelist = {}
207,563✔
261
    return lst
207,563✔
262
  end
263

264
  function _resumable:done()
206✔
265
    return resumelist[1] == nil
212,056✔
266
  end
267

268
  function _resumable:count()
206✔
269
    return #resumelist + #_resumable
12✔
270
  end
271

272
end
273

274

275

276
-- Similar to the socket set above, but tailored for the use of
277
-- sleeping threads
278
local _sleeping = {} do
206✔
279

280
  local heap = binaryheap.minUnique()
206✔
281
  local lethargy = setmetatable({}, { __mode = "k" }) -- list of coroutines sleeping without a wakeup time
206✔
282

283

284
  -- Required base implementation
285
  -----------------------------------------
286
  _sleeping.insert = fnil
206✔
287
  _sleeping.remove = fnil
206✔
288

289
  -- push a new timer on the heap
290
  function _sleeping:push(sleeptime, co)
206✔
291
    if sleeptime < 0 then
217,216✔
292
      lethargy[co] = true
3,378✔
293
    elseif sleeptime == 0 then
213,838✔
294
      _resumable:push(co)
263,532✔
295
    else
296
      heap:insert(gettime() + sleeptime, co)
8,253✔
297
    end
298
  end
299

300
  -- find the thread that should wake up to the time, if any
301
  function _sleeping:pop(time)
206✔
302
    if time < (heap:peekValue() or math.huge) then
275,203✔
303
      return
207,563✔
304
    end
305
    return heap:pop()
8,025✔
306
  end
307

308
  -- additional methods for time management
309
  -----------------------------------------
310
  function _sleeping:getnext()  -- returns delay until next sleep expires, or nil if there is none
206✔
311
    local t = heap:peekValue()
6,930✔
312
    if t then
6,930✔
313
      -- never report less than 0, because select() might block
314
      return math.max(t - gettime(), 0)
6,930✔
315
    end
316
  end
317

318
  function _sleeping:wakeup(co)
206✔
319
    if lethargy[co] then
3,426✔
320
      lethargy[co] = nil
3,318✔
321
      _resumable:push(co)
3,318✔
322
      return true
3,318✔
323
    end
324
    if heap:remove(co) then
126✔
325
      _resumable:push(co)
18✔
326
      return true
18✔
327
    end
328
    return nil, "not sleeping"
90✔
329
  end
330

331
  -- non-destructive check; unlike wakeup/cancel it doesn't remove 'co'
332
  function _sleeping:issleeping(co)
206✔
333
    if lethargy[co] then
606✔
334
      return true
564✔
335
    end
336
    return heap:valueByPayload(co) ~= nil
49✔
337
  end
338

339
  function _sleeping:cancel(co)
206✔
340
    lethargy[co] = nil
66✔
341
    heap:remove(co)
66✔
342
  end
343

344
  function _sleeping:cancelall()
206✔
345
    while heap:size() > 0 do heap:pop() end
×
346
    heap:insert(gettime() + TIMEOUT_PRECISION, core_timer_thread)
×
347
    -- lethargy is weak; copas's idle GC sweeps will clean it within a few steps
348
  end
349

350
  -- @param tos number of timeouts running
351
  function _sleeping:done(tos)
206✔
352
    -- return true if we have nothing more to do
353
    -- the timeout task doesn't qualify as work (fallbacks only),
354
    -- the lethargy also doesn't qualify as work ('dead' tasks),
355
    -- but the combination of a timeout + a lethargy can be work
356
    return heap:size() == 1       -- 1 means only the timeout-timer task is running
4,178✔
357
           and not (tos > 0 and next(lethargy))
3,582✔
358
  end
359

360
  -- gets number of threads in binaryheap and lethargy
361
  function _sleeping:status()
206✔
362
    local c = 0
12✔
363
    for _ in pairs(lethargy) do c = c + 1 end
12✔
364

365
    return heap:size(), c
14✔
366
  end
367

368
end   -- _sleeping
369

370

371

372
-------------------------------------------------------------------------------
373
-- Tracking coroutines and sockets
374
-------------------------------------------------------------------------------
375

376
local _servers = newsocketset() -- servers being handled
206✔
377
local _threads = setmetatable({}, {__mode = "k"})  -- registered threads added with addthread()
206✔
378
local _canceled = setmetatable({}, {__mode = "k"}) -- threads that are canceled and pending removal
206✔
379
local _autoclose = setmetatable({}, {__mode = "kv"}) -- sockets (value) to close when a thread (key) exits
206✔
380
local _autoclose_r = setmetatable({}, {__mode = "kv"}) -- reverse: sockets (key) to close when a thread (value) exits
206✔
381

382

383
-- for each socket we log the last read and last write times to enable the
384
-- watchdog to follow up if it takes too long.
385
-- tables contain the time, indexed by the socket
386
local _reading_log = {}
206✔
387
local _writing_log = {}
206✔
388

389
local _closed = {} -- track sockets that have been closed (list/array)
206✔
390

391
local _reading = newsocketset() -- sockets currently being read
206✔
392
local _writing = newsocketset() -- sockets currently being written
206✔
393
local _isSocketTimeout = { -- set of errors indicating a socket-timeout
206✔
394
  ["timeout"] = true,      -- default LuaSocket timeout
173✔
395
  ["wantread"] = true,     -- LuaSec specific timeout
173✔
396
  ["wantwrite"] = true,    -- LuaSec specific timeout
173✔
397
}
398

399
-------------------------------------------------------------------------------
400
-- Coroutine based socket timeouts.
401
-------------------------------------------------------------------------------
402
local user_timeouts_connect
403
local user_timeouts_send
404
local user_timeouts_receive
405
do
406
  local timeout_mt = {
206✔
407
    __mode = "k",
173✔
408
    __index = function(self, skt)
409
      -- if there is no timeout found, we insert one automatically, to block forever
410
      self[skt] = math.huge
474✔
411
      return self[skt]
474✔
412
    end,
413
  }
414

415
  user_timeouts_connect = setmetatable({}, timeout_mt)
206✔
416
  user_timeouts_send = setmetatable({}, timeout_mt)
206✔
417
  user_timeouts_receive = setmetatable({}, timeout_mt)
206✔
418
end
419

420
local useSocketTimeoutErrors = setmetatable({},{ __mode = "k" })
206✔
421

422

423
-- sto = socket-time-out
424
local sto_timeout, sto_timed_out, sto_change_queue, sto_error do
206✔
425

426
  local socket_register = setmetatable({}, { __mode = "k" })    -- socket by coroutine
206✔
427
  local operation_register = setmetatable({}, { __mode = "k" }) -- operation "read"/"write" by coroutine
206✔
428
  local timeout_flags = setmetatable({}, { __mode = "k" })      -- true if timedout, by coroutine
206✔
429

430

431
  -- The callback called when a socket timeout occurs.
432
  local function socket_callback(co)
433
    local skt = socket_register[co]
84✔
434
    local queue = operation_register[co]
84✔
435

436
    -- flag the timeout and resume the coroutine
437
    timeout_flags[co] = true
84✔
438
    _resumable:push(co)
84✔
439

440
    -- release our claim on the socket and stop watching it; the timer, not
441
    -- the readiness path, is resuming `co`, so nothing else will do this
442
    if queue == "read" then
84✔
443
      _reading:release(skt)
72✔
444
      _reading:remove(skt)
84✔
445
    elseif queue == "write" then
12✔
446
      _writing:release(skt)
12✔
447
      _writing:remove(skt)
14✔
448
    else
449
      error("bad queue name; expected 'read'/'write', got: "..tostring(queue))
×
450
    end
451
  end
452

453

454
  -- Sets a socket timeout.
455
  -- Calling it as `sto_timeout()` will cancel the timeout.
456
  -- @param skt (socket) the socket on which to operate, use 'nil' to cancel the current timeout
457
  -- @param queue (string) the queue the socket is currently in: "read" or "write"
458
  -- @param use_connect_to (bool) if truthy, use the connect timeout instead of the
459
  --   read/write timeout implied by queue. Needed because connect also uses the "write"
460
  --   queue, so the queue value alone cannot distinguish connect from send operations.
461
  -- @return true
462
  function sto_timeout(skt, queue, use_connect_to)
173✔
463
    local co = coroutine_running()
3,863,630✔
464
    socket_register[co] = skt
3,863,630✔
465
    operation_register[co] = queue
3,863,630✔
466
    timeout_flags[co] = nil
3,863,630✔
467
    if skt then
3,863,630✔
468
      local to = (use_connect_to and user_timeouts_connect[skt]) or
1,931,826✔
469
                 (queue == "read" and user_timeouts_receive[skt]) or
1,931,500✔
470
                 user_timeouts_send[skt]
15,232✔
471
      copas.timeout(to, socket_callback)
2,483,599✔
472
    else
473
      copas.timeout(0)
1,931,815✔
474
    end
475
    return true
3,863,630✔
476
  end
477

478

479
  -- Changes the timeout to a different queue (read/write).
480
  -- Only usefull with ssl-handshakes and "wantread", "wantwrite" errors, when
481
  -- the queue has to be changed, so the timeout handler knows where to find the socket.
482
  -- @param queue (string) the new queue the socket is in, must be either "read" or "write"
483
  -- @return true
484
  function sto_change_queue(queue)
173✔
485
    operation_register[coroutine_running()] = queue
957✔
486
    return true
957✔
487
  end
488

489

490
  -- Responds with `true` if the operation timed-out.
491
  function sto_timed_out()
173✔
492
    return timeout_flags[coroutine_running()]
1,269✔
493
  end
494

495

496
  -- Returns the proper timeout error
497
  function sto_error(err)
173✔
498
    return useSocketTimeoutErrors[coroutine_running()] and err or "timeout"
84✔
499
  end
500

501

502
  -- only in case of testing export some internals
503
  if _G._TEST then
206✔
504
    copas._socket_register = socket_register
6✔
505
    copas._operation_register = operation_register
6✔
506
    copas._timeout_flags = timeout_flags
6✔
507
  end
508
end
509

510

511

512
-------------------------------------------------------------------------------
513
-- Coroutine based socket I/O functions.
514
-------------------------------------------------------------------------------
515

516
-- Claims the socket for the current coroutine and yields to wait for it to
517
-- become ready, returning `true` once resumed.
518
-- @return nil + error if another coroutine is already waiting on this
519
-- socket (a bug in the caller, not a Copas failure).
520
local function wait_on(queue, skt)
521
  local claimed, err = queue:claim(skt, coroutine_running())
1,185✔
522
  if not claimed then
1,185✔
523
    return nil, err
12✔
524
  end
525
  queue:insert(skt)
1,173✔
526
  coroutine_yield(skt, queue)
1,173✔
527
  return true
1,173✔
528
end
529

530

531
-- Returns "tcp"" for plain TCP and "ssl" for ssl-wrapped sockets, so truthy
532
-- for tcp based, and falsy for udp based.
533
local isTCP do
206✔
534
  local lookup = {
206✔
535
    tcp = "tcp",
173✔
536
    SSL = "ssl",
173✔
537
  }
538

539
  function isTCP(socket)
173✔
540
    return lookup[tostring(socket):sub(1,3)]
854✔
541
  end
542
end
543

544

545
function copas.close(skt, ...)
206✔
546
  _closed[#_closed+1] = skt
228✔
547
  return skt:close(...)
228✔
548
end
549

550

551
-- nil or negative is indefinitly
552
function copas.settimeout(skt, timeout)
206✔
553
  timeout = timeout or -1
228✔
554
  if type(timeout) ~= "number" then
228✔
555
    return nil, "timeout must be 'nil' or a number"
18✔
556
  end
557

558
  return copas.settimeouts(skt, timeout, timeout, timeout)
210✔
559
end
560

561

562
-- negative is indefinitly, nil means do not change
563
function copas.settimeouts(skt, connect, send, read)
206✔
564

565
  if connect ~= nil and type(connect) ~= "number" then
456✔
566
    return nil, "connect timeout must be 'nil' or a number"
×
567
  end
568
  if connect then
456✔
569
    if connect < 0 then
456✔
570
      connect = nil
×
571
    end
572
    user_timeouts_connect[skt] = connect
456✔
573
  end
574

575

576
  if send ~= nil and type(send) ~= "number" then
456✔
577
    return nil, "send timeout must be 'nil' or a number"
×
578
  end
579
  if send then
456✔
580
    if send < 0 then
456✔
581
      send = nil
×
582
    end
583
    user_timeouts_send[skt] = send
456✔
584
  end
585

586

587
  if read ~= nil and type(read) ~= "number" then
456✔
588
    return nil, "read timeout must be 'nil' or a number"
×
589
  end
590
  if read then
456✔
591
    if read < 0 then
456✔
592
      read = nil
×
593
    end
594
    user_timeouts_receive[skt] = read
456✔
595
  end
596

597

598
  return true
456✔
599
end
600

601
-- reads a pattern from a client and yields to the reading set on timeouts
602
-- UDP: a UDP socket expects a second argument to be a number, so it MUST
603
-- be provided as the 'pattern' below defaults to a string. Will throw a
604
-- 'bad argument' error if omitted.
605
-- SECURITY: the default pattern "*l" has no maximum length, matching LuaSocket
606
-- and Lua file-io semantics. It buffers until a newline/EOF/error, and the
607
-- per-operation timeout resets on every partial receive, so it does not bound
608
-- the accumulated size either. Do not use the default line-read directly on
609
-- untrusted/remote input without an application-enforced size limit; use a
610
-- numeric (sized) pattern or receivepartial with your own cumulative cap instead.
611
function copas.receive(client, pattern, part)
206✔
612
  local s, err
613
  pattern = pattern or "*l"
1,916,229✔
614
  local current_log = _reading_log
1,916,229✔
615
  sto_timeout(client, "read")
1,916,229✔
616

617
  repeat
618
    s, err, part = client:receive(pattern, part)
1,916,803✔
619

620
    -- guarantees that high throughput doesn't take other threads to starvation
621
    if (math.random(100) > 90) then
1,916,803✔
622
      copas.pause()
192,060✔
623
    end
624

625
    if s then
1,916,803✔
626
      current_log[client] = nil
1,916,109✔
627
      sto_timeout()
1,916,109✔
628
      return s, err, part
1,916,109✔
629

630
    elseif not _isSocketTimeout[err] then
694✔
631
      current_log[client] = nil
48✔
632
      sto_timeout()
48✔
633
      return s, err, part
48✔
634

635
    elseif sto_timed_out() then
761✔
636
      current_log[client] = nil
66✔
637
      sto_timeout()
66✔
638
      return nil, sto_error(err), part
77✔
639
    end
640

641
    local queue, direction
642
    if err == "wantwrite" then -- wantwrite may be returned during SSL renegotiations
580✔
643
      queue = _writing
×
644
      direction = "write"
×
645
      current_log = _writing_log
×
646
    else
647
      queue = _reading
580✔
648
      direction = "read"
580✔
649
      current_log = _reading_log
580✔
650
    end
651

652
    current_log[client] = gettime()
580✔
653
    sto_change_queue(direction)
580✔
654
    local ok, werr = wait_on(queue, client)
580✔
655
    if not ok then
580✔
656
      current_log[client] = nil
6✔
657
      sto_timeout()
6✔
658
      return nil, werr, part
6✔
659
    end
660
  until false
574✔
661
end
662

663
-- receives data from a client over UDP. Not available for TCP.
664
-- (this is a copy of receive() method, adapted for receivefrom() use)
665
function copas.receivefrom(client, size)
206✔
666
  local s, err, port
667
  size = size or UDP_DATAGRAM_MAX
24✔
668
  sto_timeout(client, "read")
24✔
669

670
  repeat
671
    s, err, port = client:receivefrom(size) -- upon success err holds ip address
48✔
672

673
    -- garantees that high throughput doesn't take other threads to starvation
674
    if (math.random(100) > 90) then
48✔
675
      copas.pause()
6✔
676
    end
677

678
    if s then
48✔
679
      _reading_log[client] = nil
18✔
680
      sto_timeout()
18✔
681
      return s, err, port
18✔
682

683
    elseif err ~= "timeout" then
30✔
684
      _reading_log[client] = nil
×
685
      sto_timeout()
×
686
      return s, err, port
×
687

688
    elseif sto_timed_out() then
35✔
689
      _reading_log[client] = nil
6✔
690
      sto_timeout()
6✔
691
      return nil, sto_error(err), port
7✔
692
    end
693

694
    _reading_log[client] = gettime()
24✔
695
    local ok, werr = wait_on(_reading, client)
24✔
696
    if not ok then
24✔
697
      _reading_log[client] = nil
×
698
      sto_timeout()
×
699
      return nil, werr, port
×
700
    end
701
  until false
24✔
702
end
703

704
-- same as above but with special treatment when reading chunks,
705
-- unblocks on any data received.
706
function copas.receivepartial(client, pattern, part)
206✔
707
  local s, err
708
  pattern = pattern or "*l"
12✔
709
  local orig_size = #(part or "")
12✔
710
  local current_log = _reading_log
12✔
711
  sto_timeout(client, "read")
12✔
712

713
  repeat
714
    s, err, part = client:receive(pattern, part)
18✔
715

716
    -- guarantees that high throughput doesn't take other threads to starvation
717
    if (math.random(100) > 90) then
18✔
718
      copas.pause()
1✔
719
    end
720

721
    if s or (type(part) == "string" and #part > orig_size) then
18✔
722
      current_log[client] = nil
12✔
723
      sto_timeout()
12✔
724
      return s, err, part
12✔
725

726
    elseif not _isSocketTimeout[err] then
6✔
727
      current_log[client] = nil
×
728
      sto_timeout()
×
729
      return s, err, part
×
730

731
    elseif sto_timed_out() then
7✔
732
      current_log[client] = nil
×
733
      sto_timeout()
×
734
      return nil, sto_error(err), part
×
735
    end
736

737
    local queue, direction
738
    if err == "wantwrite" then
6✔
739
      queue = _writing
×
740
      direction = "write"
×
741
      current_log = _writing_log
×
742
    else
743
      queue = _reading
6✔
744
      direction = "read"
6✔
745
      current_log = _reading_log
6✔
746
    end
747

748
    current_log[client] = gettime()
6✔
749
    sto_change_queue(direction)
6✔
750
    local ok, werr = wait_on(queue, client)
6✔
751
    if not ok then
6✔
752
      current_log[client] = nil
×
753
      sto_timeout()
×
754
      return nil, werr, part
×
755
    end
756
  until false
6✔
757
end
758
copas.receivePartial = copas.receivepartial  -- compat: receivePartial is deprecated
206✔
759

760
-- sends data to a client. The operation is buffered and
761
-- yields to the writing set on timeouts
762
-- Note: from and to parameters will be ignored by/for UDP sockets
763
function copas.send(client, data, from, to)
206✔
764
  local s, err
765
  from = from or 1
15,232✔
766
  local lastIndex = from - 1
15,232✔
767
  local current_log = _writing_log
15,232✔
768
  sto_timeout(client, "write")
15,232✔
769

770
  repeat
771
    s, err, lastIndex = client:send(data, lastIndex + 1, to)
15,411✔
772

773
    -- guarantees that high throughput doesn't take other threads to starvation
774
    if (math.random(100) > 90) then
15,411✔
775
      copas.pause()
1,497✔
776
    end
777

778
    if s then
15,411✔
779
      current_log[client] = nil
15,196✔
780
      sto_timeout()
15,196✔
781
      return s, err, lastIndex
15,196✔
782

783
    elseif not _isSocketTimeout[err] then
215✔
784
      current_log[client] = nil
30✔
785
      sto_timeout()
30✔
786
      return s, err, lastIndex
30✔
787

788
    elseif sto_timed_out() then
215✔
789
      current_log[client] = nil
×
790
      sto_timeout()
×
791
      return nil, sto_error(err), lastIndex
×
792
    end
793

794
    local queue, direction
795
    if err == "wantread" then
185✔
796
      queue = _reading
×
797
      direction = "read"
×
798
      current_log = _reading_log
×
799
    else
800
      queue = _writing
185✔
801
      direction = "write"
185✔
802
      current_log = _writing_log
185✔
803
    end
804

805
    current_log[client] = gettime()
185✔
806
    sto_change_queue(direction)
185✔
807
    local ok, werr = wait_on(queue, client)
185✔
808
    if not ok then
185✔
809
      current_log[client] = nil
6✔
810
      sto_timeout()
6✔
811
      return nil, werr, lastIndex
6✔
812
    end
813
  until false
179✔
814
end
815

816
function copas.sendto(client, data, ip, port)
206✔
817
  -- deprecated; for backward compatibility only, since UDP doesn't block on sending
818
  return client:sendto(data, ip, port)
×
819
end
820

821
-- waits until connection is completed
822
function copas.connect(skt, host, port)
206✔
823
  skt:settimeout(0)
212✔
824
  local ret, err, tried_more_than_once
825
  sto_timeout(skt, "write", true)
210✔
826

827
  repeat
828
    ret, err = skt:connect(host, port)
422✔
829

830
    -- non-blocking connect on Windows results in error "Operation already
831
    -- in progress" to indicate that it is completing the request async. So essentially
832
    -- it is the same as "timeout"
833
    if ret or (err ~= "timeout" and err ~= "Operation already in progress") then
414✔
834
      _writing_log[skt] = nil
198✔
835
      sto_timeout()
198✔
836
      -- Once the async connect completes, Windows returns the error "already connected"
837
      -- to indicate it is done, so that error should be ignored. Except when it is the
838
      -- first call to connect, then it was already connected to something else and the
839
      -- error should be returned
840
      if (not ret) and (err == "already connected" and tried_more_than_once) then
198✔
841
        return 1
×
842
      end
843
      return ret, err
198✔
844

845
    elseif sto_timed_out() then
252✔
846
      _writing_log[skt] = nil
12✔
847
      sto_timeout()
12✔
848
      return nil, sto_error(err)
14✔
849
    end
850

851
    tried_more_than_once = tried_more_than_once or true
204✔
852
    _writing_log[skt] = gettime()
204✔
853
    local ok, werr = wait_on(_writing, skt)
204✔
854
    if not ok then
204✔
855
      _writing_log[skt] = nil
×
856
      sto_timeout()
×
857
      return nil, werr
×
858
    end
859
  until false
204✔
860
end
861

862

863
-- Wraps a tcp socket in an ssl socket and configures it. If the socket was
864
-- already wrapped, it does nothing and returns the socket.
865
-- @param wrap_params the parameters for the ssl-context
866
-- @return wrapped socket, or throws an error
867
local function ssl_wrap(skt, wrap_params)
868
  if isTCP(skt) == "ssl" then return skt end -- was already wrapped
238✔
869
  if not wrap_params then
120✔
870
    error("cannot wrap socket into a secure socket (using 'ssl.wrap()') without parameters/context")
×
871
  end
872

873
  ssl = ssl or require("ssl")
120✔
874
  local nskt = assert(ssl.wrap(skt, wrap_params)) -- assert, because we do not want to silently ignore this one!!
138✔
875

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

880
  local co = _autoclose_r[skt]
108✔
881
  if co then
108✔
882
    -- socket registered for autoclose, move registration to wrapped one
883
    _autoclose[co] = nskt
24✔
884
    _autoclose_r[skt] = nil
24✔
885
    _autoclose_r[nskt] = co
24✔
886
  end
887

888
  local sock_name = object_names[skt]
108✔
889
  if sock_name ~= tostring(skt) then
108✔
890
    -- socket had a custom name, so copy it over
891
    object_names[nskt] = sock_name
36✔
892
  end
893
  return nskt
108✔
894
end
895

896

897
-- For each luasec method we have a subtable, allows for future extension.
898
-- Required structure:
899
-- {
900
--   wrap = ... -- parameter to 'wrap()'; the ssl parameter table, or the context object
901
--   sni = {                  -- parameters to 'sni()'
902
--     names = string | table -- 1st parameter
903
--     strict = bool          -- 2nd parameter
904
--   }
905
-- }
906
local function normalize_sslt(sslt)
907
  local t = type(sslt)
384✔
908
  local r = setmetatable({}, {
768✔
909
    __index = function(self, key)
910
      -- a bug if this happens, here as a sanity check, just being careful since
911
      -- this is security stuff
912
      error("accessing unknown 'ssl_params' table key: "..tostring(key))
×
913
    end,
914
  })
915
  if t == "nil" then
384✔
916
    r.wrap = false
246✔
917
    r.sni = false
246✔
918

919
  elseif t == "table" then
138✔
920
    if sslt.wrap or sslt.sni then
138✔
921
      -- has the target definition (current format), copy our known keys
922
      r.wrap = sslt.wrap or false -- 'or false' because we do not want nils
96✔
923
      r.sni = sslt.sni or false -- 'or false' because we do not want nils
96✔
924
    else
925
      -- neither of our own keys is truthy, so treat it as a flat luasec
926
      -- context/wrap-params table (backward compatibility), or garbage.
927
      -- There are no default TLS settings, so we cannot detect/reject a bad
928
      -- table here. But we do not need to; LuaSec validates its mandatory
929
      -- fields (mode, protocol, etc.) itself and throws on anything
930
      -- incomplete, so this can never fail open into silent plaintext.
931
      r.wrap = sslt
42✔
932
      r.sni = false
42✔
933
    end
934

935
  elseif t == "userdata" then
×
936
    -- it's an ssl-context object for the handshake
937
    -- backward compatibility
938
    r.wrap = sslt
×
939
    r.sni = false
×
940

941
  else
942
    error("ssl parameters; did not expect type "..tostring(sslt))
×
943
  end
944

945
  return r
384✔
946
end
947

948

949
---
950
-- Peforms an (async) ssl handshake on a connected TCP client socket.
951
-- NOTE: if not ssl-wrapped already, then replace all previous socket references, with the returned new ssl wrapped socket
952
-- Throws error and does not return nil+error, as that might silently fail
953
-- in code like this;
954
--   copas.addserver(s1, function(skt)
955
--       skt = copas.wrap(skt, sparams)
956
--       skt:dohandshake()   --> without explicit error checking, this fails silently and
957
--       skt:send(body)      --> continues unencrypted
958
-- @param skt Regular LuaSocket CLIENT socket object
959
-- @param wrap_params Table with ssl parameters
960
-- @return wrapped ssl socket, or throws an error
961
function copas.dohandshake(skt, wrap_params)
206✔
962
  ssl = ssl or require("ssl")
120✔
963

964
  local nskt = ssl_wrap(skt, wrap_params)
120✔
965

966
  sto_timeout(nskt, "write", true)
108✔
967
  local queue
968

969
  repeat
970
    local success, err = nskt:dohandshake()
294✔
971

972
    if success then
294✔
973
      sto_timeout()
96✔
974
      return nskt
96✔
975

976
    elseif not _isSocketTimeout[err] then
198✔
977
      sto_timeout()
12✔
978
      error("TLS/SSL handshake failed: " .. tostring(err))
12✔
979

980
    elseif sto_timed_out() then
217✔
981
      sto_timeout()
×
982
      error("TLS/SSL handshake timeout: " .. tostring(err))
×
983

984
    elseif err == "wantwrite" then
186✔
985
      sto_change_queue("write")
×
986
      queue = _writing
×
987

988
    elseif err == "wantread" then
186✔
989
      sto_change_queue("read")
186✔
990
      queue = _reading
186✔
991

992
    else
993
      error("TLS/SSL handshake failed: " .. tostring(err))
×
994
    end
995

996
    local ok, werr = wait_on(queue, nskt)
186✔
997
    if not ok then
186✔
998
      sto_timeout()
×
999
      error("TLS/SSL handshake failed: " .. tostring(werr))
×
1000
    end
1001
  until false
186✔
1002
end
1003

1004
-- flushes a client write buffer (deprecated)
1005
function copas.flush()
206✔
1006
end
1007

1008
-- wraps a TCP socket to use Copas methods (send, receive, flush and settimeout)
1009
local _skt_mt_tcp = {
206✔
1010
      __tostring = function(self)
1011
        return tostring(self.socket).." (copas wrapped)"
18✔
1012
      end,
1013

1014
      __index = {
206✔
1015
        send = function (self, data, from, to)
1016
          return copas.send (self.socket, data, from, to)
15,226✔
1017
        end,
1018

1019
        receive = function (self, pattern, prefix)
1020
          if user_timeouts_receive[self.socket] == 0 then
1,916,206✔
1021
            return copas.receivepartial(self.socket, pattern, prefix)
12✔
1022
          end
1023
          return copas.receive(self.socket, pattern, prefix)
1,916,193✔
1024
        end,
1025

1026
        receivepartial = function (self, pattern, prefix)
1027
          return copas.receivepartial(self.socket, pattern, prefix)
×
1028
        end,
1029

1030
        flush = function (self)
1031
          return copas.flush(self.socket)
×
1032
        end,
1033

1034
        settimeout = function (self, time)
1035
          return copas.settimeout(self.socket, time)
204✔
1036
        end,
1037

1038
        settimeouts = function (self, connect, send, receive)
1039
          return copas.settimeouts(self.socket, connect, send, receive)
×
1040
        end,
1041

1042
        -- TODO: socket.connect is a shortcut, and must be provided with an alternative
1043
        -- if ssl parameters are available, it will also include a handshake
1044
        connect = function(self, ...)
1045
          local res, err = copas.connect(self.socket, ...)
210✔
1046
          -- sni errors out if it fails, so we do not need to check for errors here.
1047
          -- sni() itself returns nothing on success, so its result must not be folded into 'res'.
1048
          if res then
210✔
1049
            if self.ssl_params.sni then self:sni() end
192✔
1050
            if self.ssl_params.wrap then res, err = self:dohandshake() end
205✔
1051
          end
1052
          return res, err
204✔
1053
        end,
1054

1055
        close = function(self, ...)
1056
          return copas.close(self.socket, ...)
222✔
1057
        end,
1058

1059
        -- TODO: socket.bind is a shortcut, and must be provided with an alternative
1060
        bind = function(self, ...) return self.socket:bind(...) end,
206✔
1061

1062
        -- TODO: is this DNS related? hence blocking?
1063
        getsockname = function(self, ...)
1064
          local ok, ip, port, family = pcall(self.socket.getsockname, self.socket, ...)
×
1065
          if ok then
×
1066
            return ip, port, family
×
1067
          else
1068
            return nil, "not implemented by LuaSec"
×
1069
          end
1070
        end,
1071

1072
        getstats = function(self, ...) return self.socket:getstats(...) end,
206✔
1073

1074
        setstats = function(self, ...) return self.socket:setstats(...) end,
206✔
1075

1076
        listen = function(self, ...) return self.socket:listen(...) end,
206✔
1077

1078
        accept = function(self, ...) return self.socket:accept(...) end,
206✔
1079

1080
        setoption = function(self, ...)
1081
          local ok, res, err = pcall(self.socket.setoption, self.socket, ...)
×
1082
          if ok then
×
1083
            return res, err
×
1084
          else
1085
            return nil, "not implemented by LuaSec"
×
1086
          end
1087
        end,
1088

1089
        getoption = function(self, ...)
1090
          local ok, val, err = pcall(self.socket.getoption, self.socket, ...)
×
1091
          if ok then
×
1092
            return val, err
×
1093
          else
1094
            return nil, "not implemented by LuaSec"
×
1095
          end
1096
        end,
1097

1098
        -- TODO: is this DNS related? hence blocking?
1099
        getpeername = function(self, ...)
1100
          local ok, ip, port, family = pcall(self.socket.getpeername, self.socket, ...)
×
1101
          if ok then
×
1102
            return ip, port, family
×
1103
          else
1104
            return nil, "not implemented by LuaSec"
×
1105
          end
1106
        end,
1107

1108
        shutdown = function(self, ...) return self.socket:shutdown(...) end,
206✔
1109

1110
        sni = function(self, names, strict)
1111
          local sslp = self.ssl_params
84✔
1112
          self.socket = ssl_wrap(self.socket, sslp.wrap)
98✔
1113
          if names == nil then
84✔
1114
            names = sslp.sni.names
72✔
1115
            strict = sslp.sni.strict
72✔
1116
          end
1117
          -- sni() throws on bad parameters by itself, and returns nothing on success
1118
          return self.socket:sni(names, strict)
84✔
1119
        end,
1120

1121
        dohandshake = function(self, wrap_params)
1122
          -- copas.dohandshake() either returns the wrapped ssl socket, or throws
1123
          self.socket = copas.dohandshake(self.socket, wrap_params or self.ssl_params.wrap)
136✔
1124
          return self
96✔
1125
        end,
1126

1127
        getalpn = function(self, ...)
1128
          local ok, proto, err = pcall(self.socket.getalpn, self.socket, ...)
×
1129
          if ok then
×
1130
            return proto, err
×
1131
          else
1132
            return nil, "not a tls socket"
×
1133
          end
1134
        end,
1135

1136
        getsniname = function(self, ...)
1137
          local ok, name, err = pcall(self.socket.getsniname, self.socket, ...)
×
1138
          if ok then
×
1139
            return name, err
×
1140
          else
1141
            return nil, "not a tls socket"
×
1142
          end
1143
        end,
1144
      }
206✔
1145
}
1146

1147
-- wraps a UDP socket, copy of TCP one adapted for UDP.
1148
local _skt_mt_udp = {__index = { }}
206✔
1149
for k,v in pairs(_skt_mt_tcp) do _skt_mt_udp[k] = _skt_mt_udp[k] or v end
618✔
1150
for k,v in pairs(_skt_mt_tcp.__index) do _skt_mt_udp.__index[k] = v end
4,738✔
1151

1152
_skt_mt_udp.__index.send        = function(self, ...) return self.socket:send(...) end
212✔
1153

1154
_skt_mt_udp.__index.sendto      = function(self, ...) return self.socket:sendto(...) end
230✔
1155

1156

1157
_skt_mt_udp.__index.receive =     function (self, size)
206✔
1158
                                    return copas.receive (self.socket, (size or UDP_DATAGRAM_MAX))
18✔
1159
                                  end
1160

1161
_skt_mt_udp.__index.receivefrom = function (self, size)
206✔
1162
                                    return copas.receivefrom (self.socket, (size or UDP_DATAGRAM_MAX))
24✔
1163
                                  end
1164

1165
                                  -- TODO: is this DNS related? hence blocking?
1166
_skt_mt_udp.__index.setpeername = function(self, ...) return self.socket:setpeername(...) end
212✔
1167

1168
_skt_mt_udp.__index.setsockname = function(self, ...) return self.socket:setsockname(...) end
206✔
1169

1170
                                    -- do not close client, as it is also the server for udp.
1171
_skt_mt_udp.__index.close       = function(self, ...) return true end
218✔
1172

1173
_skt_mt_udp.__index.settimeouts = function (self, connect, send, receive)
206✔
1174
                                    return copas.settimeouts(self.socket, connect, send, receive)
×
1175
                                  end
1176

1177

1178

1179
---
1180
-- Wraps a LuaSocket socket object in an async Copas based socket object.
1181
-- @param skt The socket to wrap
1182
-- @param[opt] sslt Table with ssl parameters (see 'sslparams' in the reference docs).
1183
-- Omit the parameter to disable TLS entirely.
1184
-- @return wrapped socket object
1185
function copas.wrap (skt, sslt)
206✔
1186
  if (getmetatable(skt) == _skt_mt_tcp) or (getmetatable(skt) == _skt_mt_udp) then
420✔
1187
    return skt -- already wrapped
×
1188
  end
1189

1190
  skt:settimeout(0)
422✔
1191

1192
  if isTCP(skt) then
490✔
1193
    return setmetatable ({socket = skt, ssl_params = normalize_sslt(sslt)}, _skt_mt_tcp)
448✔
1194
  else
1195
    return setmetatable ({socket = skt}, _skt_mt_udp)
36✔
1196
  end
1197
end
1198

1199
--- Wraps a handler in a function that deals with wrapping the socket and doing the
1200
-- optional ssl handshake.
1201
function copas.handler(handler, sslparams)
206✔
1202
  -- TODO: pass a timeout value to set, and use during handshake
1203
  return function (skt, ...)
1204
    skt = copas.wrap(skt, sslparams) -- this call will normalize the sslparams table
112✔
1205
    local sslp = skt.ssl_params
96✔
1206
    -- sni doesn't return an error, just throws on bad params, so no error checking needed.
1207
    -- the wrapped dohandshake does the same, so also no error handling needed.
1208
    if sslp.sni then skt:sni(sslp.sni.names, sslp.sni.strict) end
96✔
1209
    if sslp.wrap then skt:dohandshake(sslp.wrap) end
96✔
1210
    return handler(skt, ...)
90✔
1211
  end
1212
end
1213

1214

1215
--------------------------------------------------
1216
-- Error handling
1217
--------------------------------------------------
1218

1219
local _errhandlers = setmetatable({}, { __mode = "k" })   -- error handler per coroutine
206✔
1220

1221

1222
function copas.gettraceback(msg, co, skt)
206✔
1223
  local co_str = co == nil and "nil" or copas.getthreadname(co)
38✔
1224
  local skt_str = skt == nil and "nil" or copas.getsocketname(skt)
38✔
1225
  local msg_str = msg == nil and "" or tostring(msg)
38✔
1226
  if msg_str == "" then
38✔
1227
    msg_str = ("(coroutine: %s, socket: %s)"):format(msg_str, co_str, skt_str)
×
1228
  else
1229
    msg_str = ("%s (coroutine: %s, socket: %s)"):format(msg_str, co_str, skt_str)
38✔
1230
  end
1231

1232
  if type(co) == "thread" then
38✔
1233
    -- regular Copas coroutine
1234
    return debug.traceback(co, msg_str)
38✔
1235
  end
1236
  -- not a coroutine, but the main thread, this happens if a timeout callback
1237
  -- (see `copas.timeout` causes an error (those callbacks run on the main thread).
1238
  return debug.traceback(msg_str, 2)
×
1239
end
1240

1241

1242
local function _deferror(msg, co, skt)
1243
  print(copas.gettraceback(msg, co, skt))
29✔
1244
end
1245

1246

1247
function copas.seterrorhandler(err, default)
206✔
1248
  assert(err == nil or type(err) == "function", "Expected the handler to be a function, or nil")
60✔
1249
  if default then
60✔
1250
    assert(err ~= nil, "Expected the handler to be a function when setting the default")
42✔
1251
    _deferror = err
42✔
1252
  else
1253
    _errhandlers[coroutine_running()] = err
18✔
1254
  end
1255
end
1256
copas.setErrorHandler = copas.seterrorhandler  -- deprecated; old casing
206✔
1257

1258

1259
function copas.geterrorhandler(co)
206✔
1260
  co = co or coroutine_running()
12✔
1261
  return _errhandlers[co] or _deferror
12✔
1262
end
1263

1264

1265
-- if `bool` is truthy, then the original socket errors will be returned in case of timeouts;
1266
-- `timeout, wantread, wantwrite, Operation already in progress`. If falsy, it will always
1267
-- return `timeout`.
1268
function copas.useSocketTimeoutErrors(bool)
206✔
1269
  useSocketTimeoutErrors[coroutine_running()] = not not bool -- force to a boolean
6✔
1270
end
1271

1272
-------------------------------------------------------------------------------
1273
-- Thread handling
1274
-------------------------------------------------------------------------------
1275

1276
local function _doTick (co, skt, ...)
1277
  if not co then return end
223,941✔
1278

1279
  -- if a coroutine was canceled/removed, don't resume it
1280
  if _canceled[co] then
223,941✔
1281
    _canceled[co] = nil -- also clean up the registry
18✔
1282
    _threads[co] = nil
18✔
1283
    return
18✔
1284
  end
1285

1286
  -- res: the socket (being read/write on) or the time to sleep
1287
  -- new_q: either _writing, _reading, or _sleeping
1288
  -- local time_before = gettime()
1289
  local ok, res, new_q = coroutine_resume(co, skt, ...)
223,923✔
1290
  -- local duration = gettime() - time_before
1291
  -- if duration > 1 then
1292
  --   duration = math.floor(duration * 1000)
1293
  --   pcall(_errhandlers[co] or _deferror, "task ran for "..tostring(duration).." milliseconds.", co, skt)
1294
  -- end
1295

1296
  if new_q == _reading or new_q == _writing then
223,911✔
1297
    -- we're yielding to wait on a socket; the claim was already taken by
1298
    -- the coroutine itself before it yielded (see wait_on below), so by
1299
    -- construction this can't fail here
1300
    new_q:insert (res)
1,173✔
1301
    return
1,173✔
1302
  elseif new_q == _sleeping then
222,738✔
1303
    -- we're yielding to sleep
1304
    new_q:insert (res)
217,216✔
1305
    new_q:push (res, co)
217,216✔
1306
    return
217,216✔
1307
  end
1308

1309
  -- coroutine is terminating
1310

1311
  if ok and coroutine_status(co) ~= "dead" then
5,522✔
1312
    -- it called coroutine.yield from a non-Copas function which is unexpected
1313
    ok = false
6✔
1314
    res = "coroutine.yield was called without a resume first, user-code cannot yield to Copas"
6✔
1315
  end
1316

1317
  if not ok then
5,522✔
1318
    local k, e = pcall(_errhandlers[co] or _deferror, res, co, skt)
46✔
1319
    if not k then
46✔
1320
      print("Failed executing error handler: " .. tostring(e))
×
1321
    end
1322
  end
1323

1324
  local skt_to_close = _autoclose[co]
5,522✔
1325
  if skt_to_close then
5,522✔
1326
    skt_to_close:close()
132✔
1327
    _autoclose[co] = nil
132✔
1328
    _autoclose_r[skt_to_close] = nil
132✔
1329
  end
1330

1331
  _errhandlers[co] = nil
5,522✔
1332
end
1333

1334

1335
local _accept do
206✔
1336
  local client_counters = setmetatable({}, { __mode = "k" })
206✔
1337

1338
  -- accepts a connection on socket input
1339
  function _accept(server_skt, handler)
173✔
1340
    local client_skt = server_skt:accept()
138✔
1341
    if client_skt then
138✔
1342
      local count = (client_counters[server_skt] or 0) + 1
138✔
1343
      client_counters[server_skt] = count
138✔
1344
      object_names[client_skt] = object_names[server_skt] .. ":client_" .. count
154✔
1345

1346
      client_skt:settimeout(0)
138✔
1347
      copas.settimeouts(client_skt, user_timeouts_connect[server_skt],  -- copy server socket timeout settings
276✔
1348
        user_timeouts_send[server_skt], user_timeouts_receive[server_skt])
154✔
1349

1350
      local co = coroutine_create(handler)
138✔
1351
      object_names[co] = object_names[server_skt] .. ":handler_" .. count
138✔
1352

1353
      if copas.autoclose then
138✔
1354
        _autoclose[co] = client_skt
138✔
1355
        _autoclose_r[client_skt] = co
138✔
1356
      end
1357

1358
      _doTick(co, client_skt)
138✔
1359
    end
1360
  end
1361
end
1362

1363
-------------------------------------------------------------------------------
1364
-- Adds a server/handler pair to Copas dispatcher
1365
-------------------------------------------------------------------------------
1366

1367
do
1368
  local function addTCPserver(server, handler, timeout, name)
1369
    server:settimeout(0)
108✔
1370
    if name then
108✔
1371
      object_names[server] = name
×
1372
    end
1373
    _servers[server] = handler
108✔
1374
    _reading:insert(server)
108✔
1375
    if timeout then
108✔
1376
      copas.settimeout(server, timeout)
18✔
1377
    end
1378
  end
1379

1380
  local function addUDPserver(server, handler, timeout, name)
1381
    server:settimeout(0)
×
1382
    local co = coroutine_create(handler)
×
1383
    if name then
×
1384
      object_names[server] = name
×
1385
    end
1386
    object_names[co] = object_names[server]..":handler"
×
1387
    _reading:insert(server)
×
1388
    if timeout then
×
1389
      copas.settimeout(server, timeout)
×
1390
    end
1391
    _doTick(co, server)
×
1392
  end
1393

1394

1395
  function copas.addserver(server, handler, timeout, name)
206✔
1396
    if isTCP(server) then
126✔
1397
      addTCPserver(server, handler, timeout, name)
126✔
1398
    else
1399
      addUDPserver(server, handler, timeout, name)
×
1400
    end
1401
  end
1402
end
1403

1404

1405
function copas.removeserver(server, keep_open)
206✔
1406
  local skt = server
102✔
1407
  local mt = getmetatable(server)
102✔
1408
  if mt == _skt_mt_tcp or mt == _skt_mt_udp then
102✔
1409
    skt = server.socket
×
1410
  end
1411

1412
  _servers:remove(skt)
102✔
1413
  _reading:remove(skt)
102✔
1414

1415
  if keep_open then
102✔
1416
    return true
18✔
1417
  end
1418
  return server:close()
84✔
1419
end
1420

1421

1422

1423
-------------------------------------------------------------------------------
1424
-- Adds an new coroutine thread to Copas dispatcher
1425
-------------------------------------------------------------------------------
1426
function copas.addnamedthread(name, handler, ...)
206✔
1427
  if type(name) == "function" and type(handler) == "string" then
5,698✔
1428
    -- old call, flip args for compatibility
1429
    name, handler = handler, name
×
1430
  end
1431

1432
  -- create a coroutine that skips the first argument, which is always the socket
1433
  -- passed by the scheduler, but `nil` in case of a task/thread
1434
  local thread = coroutine_create(function(_, ...)
11,396✔
1435
    copas.pause()
5,698✔
1436
    return handler(...)
5,668✔
1437
  end)
1438
  if name then
5,698✔
1439
    object_names[thread] = name
586✔
1440
  end
1441

1442
  _threads[thread] = true -- register this thread so it can be removed
5,698✔
1443
  _doTick (thread, nil, ...)
5,698✔
1444
  return thread
5,698✔
1445
end
1446

1447

1448
function copas.addthread(handler, ...)
206✔
1449
  return copas.addnamedthread(nil, handler, ...)
5,046✔
1450
end
1451

1452

1453
function copas.removethread(thread)
206✔
1454
  -- if the specified coroutine is registered, add it to the canceled table so
1455
  -- that next time it tries to resume it exits.
1456
  _canceled[thread] = _threads[thread or 0]
66✔
1457
  _sleeping:cancel(thread)
66✔
1458
end
1459

1460

1461

1462
-------------------------------------------------------------------------------
1463
-- Sleep/pause management functions
1464
-------------------------------------------------------------------------------
1465

1466
-- yields the current coroutine and wakes it after 'sleeptime' seconds.
1467
-- If sleeptime < 0 then it sleeps until explicitly woken up using 'wakeup'
1468
-- TODO: deprecated, remove in next major
1469
function copas.sleep(sleeptime)
206✔
1470
  coroutine_yield((sleeptime or 0), _sleeping)
×
1471
end
1472

1473

1474
-- yields the current coroutine and wakes it after 'sleeptime' seconds.
1475
-- if sleeptime < 0 then it sleeps 0 seconds.
1476
function copas.pause(sleeptime)
206✔
1477
  local s = gettime()
213,838✔
1478
  if sleeptime and sleeptime > 0 then
213,838✔
1479
    coroutine_yield(sleeptime, _sleeping)
9,589✔
1480
  else
1481
    coroutine_yield(0, _sleeping)
205,585✔
1482
  end
1483
  return gettime() - s
213,596✔
1484
end
1485

1486

1487
-- yields the current coroutine until explicitly woken up using 'wakeup'
1488
function copas.pauseforever()
206✔
1489
  local s = gettime()
3,378✔
1490
  coroutine_yield(-1, _sleeping)
3,378✔
1491
  return gettime() - s
3,318✔
1492
end
1493

1494

1495
-- Wakes up a sleeping coroutine 'co'.
1496
-- @return true on success, or nil+"not sleeping" if 'co' wasn't sleeping
1497
-- (eg. it was already woken up, finished, or canceled through `copas.removethread`).
1498
function copas.wakeup(co)
206✔
1499
  return _sleeping:wakeup(co)
3,426✔
1500
end
1501

1502

1503
-- Checks whether a coroutine 'co' is currently sleeping (paused or
1504
-- paused-forever), without waking it up. Useful to detect a coroutine
1505
-- that was canceled (eg. through `copas.removethread`) while it was
1506
-- expected to still be waiting.
1507
function copas.issleeping(co)
206✔
1508
  return _sleeping:issleeping(co)
606✔
1509
end
1510

1511

1512

1513
-------------------------------------------------------------------------------
1514
-- Timeout management
1515
-------------------------------------------------------------------------------
1516

1517
do
1518
  local timeout_register = setmetatable({}, { __mode = "k" })
206✔
1519
  local timerwheel = require("timerwheel").new({
413✔
1520
      now = gettime,
206✔
1521
      precision = TIMEOUT_PRECISION,
206✔
1522
      ringsize = math.floor(60*60*24/TIMEOUT_PRECISION),  -- ring size 1 day
206✔
1523
      err_handler = function(err)
1524
        return _deferror(err, core_timer_thread)
16✔
1525
      end,
1526
    })
1527

1528
  core_timer_thread = copas.addnamedthread("copas_core_timer", function()
412✔
1529
    while true do
1530
      copas.pause(TIMEOUT_PRECISION)
7,107✔
1531
      timerwheel:step()
8,061✔
1532
    end
1533
  end)
1534

1535
  -- get the number of timeouts running
1536
  function copas.gettimeouts()
206✔
1537
    return timerwheel:count()
3,594✔
1538
  end
1539

1540
  --- Sets the timeout for the current coroutine.
1541
  -- @param delay delay (seconds), use 0 (or math.huge) to cancel the timerout
1542
  -- @param callback function with signature: `function(coroutine)` where coroutine is the routine that timed-out
1543
  -- @return true
1544
  function copas.timeout(delay, callback)
206✔
1545
    local co = coroutine_running()
3,868,770✔
1546
    local existing_timer = timeout_register[co]
3,868,770✔
1547

1548
    if existing_timer then
3,868,770✔
1549
      timerwheel:cancel(existing_timer)
4,566✔
1550
    end
1551

1552
    if delay > 0 and delay ~= math.huge then
3,868,770✔
1553
      timeout_register[co] = timerwheel:set(delay, callback, co)
7,185✔
1554
    elseif delay == 0 or delay == math.huge then
3,862,616✔
1555
      timeout_register[co] = nil
3,862,616✔
1556
    else
1557
      error("timout value must be greater than or equal to 0, got: "..tostring(delay))
×
1558
    end
1559

1560
    return true
3,868,770✔
1561
  end
1562

1563
end
1564

1565

1566
-------------------------------------------------------------------------------
1567
-- main tasks: manage readable and writable socket sets
1568
-------------------------------------------------------------------------------
1569
-- a task is an object with a required method `step()` that deals with a
1570
-- single step for that task.
1571

1572
local _tasks = {} do
206✔
1573
  function _tasks:add(tsk)
206✔
1574
    _tasks[#_tasks + 1] = tsk
824✔
1575
  end
1576
end
1577

1578

1579
-- a task to check ready to read events
1580
local _readable_task = {} do
206✔
1581

1582
  _readable_task._events = {}
206✔
1583

1584
  local function tick(skt)
1585
    local handler = _servers[skt]
856✔
1586
    if handler then
856✔
1587
      _accept(skt, handler)
161✔
1588
    else
1589
      _reading:remove(skt)
718✔
1590
      _doTick(_reading:release(skt), skt)
845✔
1591
    end
1592
  end
1593

1594
  function _readable_task:step()
206✔
1595
    for _, skt in ipairs(self._events) do
208,423✔
1596
      tick(skt)
856✔
1597
    end
1598
  end
1599

1600
  _tasks:add(_readable_task)
239✔
1601
end
1602

1603

1604
-- a task to check ready to write events
1605
local _writable_task = {} do
206✔
1606

1607
  _writable_task._events = {}
206✔
1608

1609
  local function tick(skt)
1610
    _writing:remove(skt)
371✔
1611
    _doTick(_writing:release(skt), skt)
432✔
1612
  end
1613

1614
  function _writable_task:step()
206✔
1615
    for _, skt in ipairs(self._events) do
207,934✔
1616
      tick(skt)
371✔
1617
    end
1618
  end
1619

1620
  _tasks:add(_writable_task)
239✔
1621
end
1622

1623

1624

1625
-- sleeping threads task
1626
local _sleeping_task = {} do
206✔
1627

1628
  function _sleeping_task:step()
206✔
1629
    local now = gettime()
207,563✔
1630

1631
    local co = _sleeping:pop(now)
207,563✔
1632
    while co do
215,588✔
1633
      -- we're pushing them to _resumable, since that list will be replaced before
1634
      -- executing. This prevents tasks running twice in a row with pause(0) for example.
1635
      -- So here we won't execute, but at _resumable step which is next
1636
      _resumable:push(co)
8,025✔
1637
      co = _sleeping:pop(now)
9,359✔
1638
    end
1639
  end
1640

1641
  _tasks:add(_sleeping_task)
206✔
1642
end
1643

1644

1645

1646
-- resumable threads task
1647
local _resumable_task = {} do
206✔
1648

1649
  function _resumable_task:step()
206✔
1650
    -- replace the resume list before iterating, so items placed in there
1651
    -- will indeed end up in the next copas step, not in this one, and not
1652
    -- create a loop
1653
    local resumelist = _resumable:clear_resumelist()
207,563✔
1654

1655
    for _, co in ipairs(resumelist) do
424,571✔
1656
      _doTick(co)
217,016✔
1657
    end
1658
  end
1659

1660
  _tasks:add(_resumable_task)
206✔
1661
end
1662

1663

1664
-------------------------------------------------------------------------------
1665
-- Checks for reads and writes on sockets
1666
-------------------------------------------------------------------------------
1667
local _select_plain do
206✔
1668

1669
  local last_cleansing = 0
206✔
1670
  local duration = function(t2, t1) return t2-t1 end
207,683✔
1671

1672
  if not socket then
206✔
1673
    -- socket module unavailable, switch to luasystem sleep
1674
    _select_plain = block_sleep
6✔
1675
  else
1676
    -- use socket.select to handle socket-io
1677
    _select_plain = function(timeout)
1678
      local err
1679
      local now = gettime()
207,477✔
1680

1681
      -- remove any closed sockets to prevent select from hanging on them
1682
      if _closed[1] then
207,477✔
1683
        for i, skt in ipairs(_closed) do
452✔
1684
          _closed[i] = { _reading:remove(skt), _writing:remove(skt) }
304✔
1685
        end
1686
      end
1687

1688
      _readable_task._events, _writable_task._events, err = socket.select(_reading, _writing, timeout)
207,477✔
1689
      local r_events, w_events = _readable_task._events, _writable_task._events
207,477✔
1690

1691
      -- inject closed sockets in readable/writeable task so they can error out properly
1692
      if _closed[1] then
207,477✔
1693
        for i, skts in ipairs(_closed) do
452✔
1694
          _closed[i] = nil
228✔
1695
          r_events[#r_events+1] = skts[1]
228✔
1696
          w_events[#w_events+1] = skts[2]
228✔
1697
        end
1698
      end
1699

1700
      if duration(now, last_cleansing) > WATCH_DOG_TIMEOUT then
265,743✔
1701
        last_cleansing = now
188✔
1702

1703
        -- Check all sockets selected for reading, and check how long they have been waiting
1704
        -- for data already, without select returning them as readable
1705
        for skt,time in pairs(_reading_log) do
188✔
1706
          if not r_events[skt] and duration(now, time) > WATCH_DOG_TIMEOUT then
×
1707
            -- This one timedout while waiting to become readable, so move
1708
            -- it in the readable list and try and read anyway, despite not
1709
            -- having been returned by select
1710
            _reading_log[skt] = nil
×
1711
            r_events[#r_events + 1] = skt
×
1712
            r_events[skt] = #r_events
×
1713
          end
1714
        end
1715

1716
        -- Do the same for writing
1717
        for skt,time in pairs(_writing_log) do
188✔
1718
          if not w_events[skt] and duration(now, time) > WATCH_DOG_TIMEOUT then
×
1719
            _writing_log[skt] = nil
×
1720
            w_events[#w_events + 1] = skt
×
1721
            w_events[skt] = #w_events
×
1722
          end
1723
        end
1724
      end
1725

1726
      if err == "timeout" and #r_events + #w_events > 0 then
207,477✔
1727
        return nil
6✔
1728
      else
1729
        return err
207,471✔
1730
      end
1731
    end
1732
  end
1733
end
1734

1735

1736

1737
-------------------------------------------------------------------------------
1738
-- Dispatcher loop step.
1739
-- Listen to client requests and handles them
1740
-- Returns false if no socket-data was handled, or true if there was data
1741
-- handled (or nil + error message)
1742
-------------------------------------------------------------------------------
1743

1744
local copas_stats
1745
local min_ever, max_ever
1746

1747
local _select = _select_plain
206✔
1748

1749
-- instrumented version of _select() to collect stats
1750
local _select_instrumented = function(timeout)
1751
  if copas_stats then
×
1752
    local step_duration = gettime() - copas_stats.step_start
×
1753
    copas_stats.duration_max = math.max(copas_stats.duration_max, step_duration)
×
1754
    copas_stats.duration_min = math.min(copas_stats.duration_min, step_duration)
×
1755
    copas_stats.duration_tot = copas_stats.duration_tot + step_duration
×
1756
    copas_stats.steps = copas_stats.steps + 1
×
1757
  else
1758
    copas_stats = {
×
1759
      duration_max = -1,
1760
      duration_min = 999999,
1761
      duration_tot = 0,
1762
      steps = 0,
1763
    }
1764
  end
1765

1766
  local err = _select_plain(timeout)
×
1767

1768
  local now = gettime()
×
1769
  copas_stats.time_start = copas_stats.time_start or now
×
1770
  copas_stats.step_start = now
×
1771

1772
  return err
×
1773
end
1774

1775

1776
function copas.step(timeout)
206✔
1777
  -- Need to wake up the select call in time for the next sleeping event
1778
  if not _resumable:done() then
265,848✔
1779
    timeout = 0
200,637✔
1780
  else
1781
    timeout = math.min(_sleeping:getnext(), timeout or math.huge)
8,085✔
1782
  end
1783

1784
  local err = _select(timeout)
207,567✔
1785

1786
  for _, tsk in ipairs(_tasks) do
1,037,815✔
1787
    tsk:step()
830,260✔
1788
  end
1789

1790
  if err then
207,555✔
1791
    if err == "timeout" then
206,490✔
1792
      if timeout + 0.01 > TIMEOUT_PRECISION and math.random(100) > 90 then
206,400✔
1793
        -- we were idle, so occasionally do a GC sweep to ensure lingering
1794
        -- sockets are closed, and we don't accidentally block the loop from
1795
        -- exiting
1796
        collectgarbage()
502✔
1797
      end
1798
      return false
206,400✔
1799
    end
1800
    return nil, err
90✔
1801
  end
1802

1803
  return true
1,065✔
1804
end
1805

1806

1807
-------------------------------------------------------------------------------
1808
-- Check whether there is something to do.
1809
-- returns false if there are no sockets for read/write nor tasks scheduled
1810
-- (which means Copas is in an empty spin)
1811
-------------------------------------------------------------------------------
1812
function copas.finished()
206✔
1813
  return #_reading == 0 and #_writing == 0 and _resumable:done() and _sleeping:done(copas.gettimeouts())
209,487✔
1814
end
1815

1816

1817
local resetexit do
206✔
1818
  local exit_semaphore, exiting
1819

1820
  function resetexit()
173✔
1821
    exit_semaphore = copas.semaphore.new(1, 0, math.huge)
478✔
1822
    exiting = false
386✔
1823
  end
1824

1825
  -- Signals tasks to exit. But only if they check for it. By calling `copas.exiting`
1826
  -- they can check if they should exit. Or by calling `copas.waitforexit` they can
1827
  -- wait until the exit signal is given.
1828
  function copas.exit()
206✔
1829
    if exiting then return end
374✔
1830
    exiting = true
374✔
1831
    exit_semaphore:destroy()
374✔
1832
  end
1833

1834
  -- returns whether Copas is in the process of exiting. Exit can be started by
1835
  -- calling `copas.exit()`.
1836
  function copas.exiting()
239✔
1837
    return exiting
742✔
1838
  end
1839

1840
  -- Pauses the current coroutine until Copas is exiting. To be used as an exit
1841
  -- signal for tasks that need to clean up before exiting.
1842
  function copas.waitforexit()
239✔
1843
    exit_semaphore:take(1)
12✔
1844
  end
1845
end
1846

1847

1848
--- Forcibly cancels all pending work and signals exit.
1849
-- Intended for test teardown only. Abandons all registered threads and sockets
1850
-- without giving them a chance to clean up. After this call copas.finished()
1851
-- will return true and the loop will exit. The module is left in a clean state
1852
-- ready for the next copas.loop() call.
1853
function copas.cancelall()
206✔
1854
  -- 1. clear resumable queue
1855
  _resumable:clear_resumelist()
×
1856

1857
  -- 2. drain sleeping heap
1858
  _sleeping:cancelall()
×
1859

1860
  -- 3. close and drain reading sockets
1861
  while _reading[1] do
×
1862
    copas.close(_reading[1])
×
1863
    _reading:remove(_reading[1])
×
1864
  end
1865

1866
  -- 4. close and drain writing sockets
1867
  while _writing[1] do
×
1868
    copas.close(_writing[1])
×
1869
    _writing:remove(_writing[1])
×
1870
  end
1871

1872
  -- 5. remove all servers
1873
  while _servers[1] do
×
1874
    copas.removeserver(_servers[1])
×
1875
  end
1876

1877
  -- 6. clear non-weak ancillary tables
1878
  _closed = {}
×
1879
  _reading_log = {}
×
1880
  _writing_log = {}
×
1881

1882
  -- 7. signal exit
1883
  copas.exit()
×
1884
end
1885

1886

1887
local _getstats do
206✔
1888
  local _getstats_instrumented, _getstats_plain
1889

1890

1891
  function _getstats_plain(enable)
173✔
1892
    -- this function gets hit if turned off, so turn on if true
1893
    if enable == true then
12✔
1894
      _select = _select_instrumented
×
1895
      _getstats = _getstats_instrumented
×
1896
      -- reset stats
1897
      min_ever = nil
×
1898
      max_ever = nil
×
1899
      copas_stats = nil
×
1900
    end
1901
    return {}
12✔
1902
  end
1903

1904

1905
  -- convert from seconds to millisecs, with microsec precision
1906
  local function useconds(t)
1907
    return math.floor((t * 1000000) + 0.5) / 1000
×
1908
  end
1909
  -- convert from seconds to seconds, with millisec precision
1910
  local function mseconds(t)
1911
    return math.floor((t * 1000) + 0.5) / 1000
×
1912
  end
1913

1914

1915
  function _getstats_instrumented(enable)
173✔
1916
    if enable == false then
×
1917
      _select = _select_plain
×
1918
      _getstats = _getstats_plain
×
1919
      -- instrumentation disabled, so switch to the plain implementation
1920
      return _getstats(enable)
×
1921
    end
1922
    if (not copas_stats) or (copas_stats.step == 0) then
×
1923
      return {}
×
1924
    end
1925
    local stats = copas_stats
×
1926
    copas_stats = nil
×
1927
    min_ever = math.min(min_ever or 9999999, stats.duration_min)
×
1928
    max_ever = math.max(max_ever or 0, stats.duration_max)
×
1929
    stats.duration_min_ever = min_ever
×
1930
    stats.duration_max_ever = max_ever
×
1931
    stats.duration_avg = stats.duration_tot / stats.steps
×
1932
    stats.step_start = nil
×
1933
    stats.time_end = gettime()
×
1934
    stats.time_tot = stats.time_end - stats.time_start
×
1935
    stats.time_avg = stats.time_tot / stats.steps
×
1936

1937
    stats.duration_avg = useconds(stats.duration_avg)
×
1938
    stats.duration_max = useconds(stats.duration_max)
×
1939
    stats.duration_max_ever = useconds(stats.duration_max_ever)
×
1940
    stats.duration_min = useconds(stats.duration_min)
×
1941
    stats.duration_min_ever = useconds(stats.duration_min_ever)
×
1942
    stats.duration_tot = useconds(stats.duration_tot)
×
1943
    stats.time_avg = useconds(stats.time_avg)
×
1944
    stats.time_start = mseconds(stats.time_start)
×
1945
    stats.time_end = mseconds(stats.time_end)
×
1946
    stats.time_tot = mseconds(stats.time_tot)
×
1947
    return stats
×
1948
  end
1949

1950
  _getstats = _getstats_plain
206✔
1951
end
1952

1953

1954
function copas.status(enable_stats)
206✔
1955
  local res = _getstats(enable_stats)
12✔
1956
  res.running = not not copas.running
12✔
1957
  res.timeout = copas.gettimeouts()
14✔
1958
  res.timer, res.inactive = _sleeping:status()
14✔
1959
  res.read = #_reading
12✔
1960
  res.write = #_writing
12✔
1961
  res.active = _resumable:count()
14✔
1962
  return res
12✔
1963
end
1964

1965

1966
-------------------------------------------------------------------------------
1967
-- Dispatcher endless loop.
1968
-- Listen to client requests and handles them forever
1969
-------------------------------------------------------------------------------
1970
function copas.loop(initializer, timeout)
239✔
1971
  if type(initializer) == "function" then
386✔
1972
    copas.addnamedthread("copas_initializer", initializer)
211✔
1973
  else
1974
    timeout = initializer or timeout
204✔
1975
  end
1976

1977
  resetexit()
386✔
1978
  copas.running = true
386✔
1979
  while true do
1980
    copas.step(timeout)
207,567✔
1981
    if copas.finished() then
265,834✔
1982
      if copas.exiting() then
863✔
1983
        break
185✔
1984
      end
1985
      copas.exit()
368✔
1986
    end
1987
  end
1988
  copas.running = false
374✔
1989
end
1990

1991

1992
-------------------------------------------------------------------------------
1993
-- Naming sockets and coroutines.
1994
-------------------------------------------------------------------------------
1995
do
1996
  local function realsocket(skt)
1997
    local mt = getmetatable(skt)
90✔
1998
    if mt == _skt_mt_tcp or mt == _skt_mt_udp then
90✔
1999
      return skt.socket
90✔
2000
    else
2001
      return skt
×
2002
    end
2003
  end
2004

2005

2006
  function copas.setsocketname(name, skt)
239✔
2007
    assert(type(name) == "string", "expected arg #1 to be a string")
90✔
2008
    skt = assert(realsocket(skt), "expected arg #2 to be a socket")
105✔
2009
    object_names[skt] = name
90✔
2010
  end
2011

2012

2013
  function copas.getsocketname(skt)
239✔
2014
    skt = assert(realsocket(skt), "expected arg #1 to be a socket")
×
2015
    return object_names[skt]
×
2016
  end
2017
end
2018

2019

2020
function copas.setthreadname(name, coro)
239✔
2021
  assert(type(name) == "string", "expected arg #1 to be a string")
60✔
2022
  coro = coro or coroutine_running()
60✔
2023
  assert(type(coro) == "thread", "expected arg #2 to be a coroutine or nil")
60✔
2024
  object_names[coro] = name
60✔
2025
end
2026

2027

2028
function copas.getthreadname(coro)
239✔
2029
  coro = coro or coroutine_running()
38✔
2030
  assert(type(coro) == "thread", "expected arg #1 to be a coroutine or nil")
38✔
2031
  return object_names[coro]
40✔
2032
end
2033

2034
-------------------------------------------------------------------------------
2035
-- Debug functionality.
2036
-------------------------------------------------------------------------------
2037
do
2038
  copas.debug = {}
206✔
2039

2040
  local log_core    -- if truthy, the core-timer will also be logged
2041
  local debug_log   -- function used as logger
2042

2043

2044
  local debug_yield = function(skt, queue)
2045
    local name = object_names[coroutine_running()]
4,002✔
2046

2047
    if log_core or name ~= "copas_core_timer" then
4,002✔
2048
      if queue == _sleeping then
3,982✔
2049
        debug_log("yielding '", name, "' to SLEEP for ", skt," seconds")
3,924✔
2050

2051
      elseif queue == _writing then
58✔
2052
        debug_log("yielding '", name, "' to WRITE on '", object_names[skt], "'")
14✔
2053

2054
      elseif queue == _reading then
46✔
2055
        debug_log("yielding '", name, "' to READ on '", object_names[skt], "'")
48✔
2056

2057
      else
2058
        debug_log("thread '", name, "' yielding to unexpected queue; ", tostring(queue), " (", type(queue), ")", debug.traceback())
×
2059
      end
2060
    end
2061

2062
    return coroutine.yield(skt, queue)
4,002✔
2063
  end
2064

2065

2066
  local debug_resume = function(coro, skt, ...)
2067
    local name = object_names[coro]
4,014✔
2068

2069
    if skt then
4,014✔
2070
      debug_log("resuming '", name, "' for socket '", object_names[skt], "'")
58✔
2071
    else
2072
      if log_core or name ~= "copas_core_timer" then
3,956✔
2073
        debug_log("resuming '", name, "'")
3,936✔
2074
      end
2075
    end
2076
    return coroutine.resume(coro, skt, ...)
4,014✔
2077
  end
2078

2079

2080
  local debug_create = function(f)
2081
    local f_wrapped = function(...)
2082
      local results = pack(f(...))
14✔
2083
      debug_log("exiting '", object_names[coroutine_running()], "'")
12✔
2084
      return unpack(results)
12✔
2085
    end
2086

2087
    return coroutine.create(f_wrapped)
12✔
2088
  end
2089

2090

2091
  debug_log = fnil
206✔
2092

2093

2094
  -- enables debug output for all coroutine operations.
2095
  function copas.debug.start(logger, core)
412✔
2096
    log_core = core
6✔
2097
    debug_log = logger or print
6✔
2098
    coroutine_yield = debug_yield
6✔
2099
    coroutine_resume = debug_resume
6✔
2100
    coroutine_create = debug_create
6✔
2101
  end
2102

2103

2104
  -- disables debug output for coroutine operations.
2105
  function copas.debug.stop()
412✔
2106
    debug_log = fnil
×
2107
    coroutine_yield = coroutine.yield
×
2108
    coroutine_resume = coroutine.resume
×
2109
    coroutine_create = coroutine.create
×
2110
  end
2111

2112
  do
2113
    local call_id = 0
206✔
2114

2115
    -- Description table of socket functions for debug output.
2116
    -- each socket function name has TWO entries;
2117
    -- 'name_in' and 'name_out', each being an array of names/descriptions of respectively
2118
    -- input parameters and return values.
2119
    -- If either table has a 'callback' key, then that is a function that will be called
2120
    -- with the parameters/return-values for further inspection.
2121
    local args = {
206✔
2122
      settimeout_in = {
206✔
2123
        "socket ",
173✔
2124
        "seconds",
173✔
2125
        "mode   ",
2126
      },
206✔
2127
      settimeout_out = {
206✔
2128
        "success",
173✔
2129
        "error  ",
2130
      },
206✔
2131
      connect_in = {
206✔
2132
        "socket ",
173✔
2133
        "address",
173✔
2134
        "port   ",
2135
      },
206✔
2136
      connect_out = {
206✔
2137
        "success",
173✔
2138
        "error  ",
2139
      },
206✔
2140
      getfd_in = {
206✔
2141
        "socket ",
2142
        -- callback = function(...)
2143
        --   print(debug.traceback("called from:", 4))
2144
        -- end,
2145
      },
206✔
2146
      getfd_out = {
206✔
2147
        "fd",
2148
      },
206✔
2149
      send_in = {
206✔
2150
        "socket   ",
173✔
2151
        "data     ",
173✔
2152
        "idx-start",
173✔
2153
        "idx-end  ",
2154
      },
206✔
2155
      send_out = {
206✔
2156
        "last-idx-send    ",
173✔
2157
        "error            ",
173✔
2158
        "err-last-idx-send",
2159
      },
206✔
2160
      receive_in = {
206✔
2161
        "socket ",
173✔
2162
        "pattern",
173✔
2163
        "prefix ",
2164
      },
206✔
2165
      receive_out = {
206✔
2166
        "received    ",
173✔
2167
        "error       ",
173✔
2168
        "partial data",
2169
      },
206✔
2170
      dirty_in = {
206✔
2171
        "socket",
2172
        -- callback = function(...)
2173
        --   print(debug.traceback("called from:", 4))
2174
        -- end,
2175
      },
206✔
2176
      dirty_out = {
206✔
2177
        "data in read-buffer",
2178
      },
206✔
2179
      close_in = {
206✔
2180
        "socket",
2181
        -- callback = function(...)
2182
        --   print(debug.traceback("called from:", 4))
2183
        -- end,
2184
      },
206✔
2185
      close_out = {
206✔
2186
        "success",
173✔
2187
        "error",
2188
      },
206✔
2189
    }
2190
    local function print_call(func, msg, ...)
2191
      print(msg)
420✔
2192
      local arg = pack(...)
420✔
2193
      local desc = args[func] or {}
420✔
2194
      for i = 1, math.max(arg.n, #desc) do
984✔
2195
        local value = arg[i]
564✔
2196
        if type(value) == "string" then
564✔
2197
          local xvalue = value:sub(1,30)
36✔
2198
          if xvalue ~= value then
36✔
2199
            xvalue = xvalue .."(...truncated)"
×
2200
          end
2201
          print("\t"..(desc[i] or i)..": '"..tostring(xvalue).."' ("..type(value).." #"..#value..")")
36✔
2202
        else
2203
          print("\t"..(desc[i] or i)..": '"..tostring(value).."' ("..type(value)..")")
528✔
2204
        end
2205
      end
2206
      if desc.callback then
420✔
2207
        desc.callback(...)
×
2208
      end
2209
    end
2210

2211
    local debug_mt = {
206✔
2212
      __index = function(self, key)
2213
        local value = self.__original_socket[key]
210✔
2214
        if type(value) ~= "function" then
210✔
2215
          return value
×
2216
        end
2217
        return function(self2, ...)
2218
            local my_id = call_id + 1
210✔
2219
            call_id = my_id
210✔
2220
            local results
2221

2222
            if self2 ~= self then
210✔
2223
              -- there is no self
2224
              print_call(tostring(key).."_in", my_id .. "-calling '"..tostring(key) .. "' with; ", self, ...)
×
2225
              results = pack(value(self, ...))
×
2226
            else
2227
              print_call(tostring(key).."_in", my_id .. "-calling '" .. tostring(key) .. "' with; ", self.__original_socket, ...)
210✔
2228
              results = pack(value(self.__original_socket, ...))
242✔
2229
            end
2230
            print_call(tostring(key).."_out", my_id .. "-results '"..tostring(key) .. "' returned; ", unpack(results))
242✔
2231
            return unpack(results)
210✔
2232
          end
2233
      end,
2234
      __tostring = function(self)
2235
        return tostring(self.__original_socket)
48✔
2236
      end
2237
    }
2238

2239

2240
    -- wraps a socket (copas or luasocket) in a debug version printing all calls
2241
    -- and their parameters/return values. Extremely noisy!
2242
    -- returns the wrapped socket.
2243
    -- NOTE: only for plain sockets, will not support TLS
2244
    function copas.debug.socket(original_skt)
412✔
2245
      if (getmetatable(original_skt) == _skt_mt_tcp) or (getmetatable(original_skt) == _skt_mt_udp) then
12✔
2246
        -- already wrapped as Copas socket, so recurse with the original luasocket one
2247
        original_skt.socket = copas.debug.socket(original_skt.socket)
×
2248
        return original_skt
×
2249
      end
2250

2251
      local proxy = setmetatable({
24✔
2252
        __original_socket = original_skt
12✔
2253
      }, debug_mt)
12✔
2254

2255
      return proxy
12✔
2256
    end
2257
  end
2258
end
2259

2260

2261
return copas
206✔
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