This file is indexed.

/usr/share/tcltk/tcllib1.19/udpcluster/udpcluster.tcl is in tcllib 1.19-dfsg-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
# -*- tcl -*-
# ### ### ### ######### ######### #########
## Name Service - Cluster

# ### ### ### ######### ######### #########
## Requirements

package require Tcl 8.5
package require comm             ; # Generic message transport
package require interp           ; # Interpreter helpers.
package require logger           ; # Tracing internal activity
package require uuid
package require cron 2.0
package require nettool 0.5.2
package require udp
package require dicttool

namespace eval ::comm {}
::namespace eval ::cluster {}

###
# This package implements an ad/hoc zero configuration
# like network of comm (and other) network connections
###

###
# topic: 5cffdc91e554c923ebe43df13fac77d5
###
proc ::cluster::broadcast {args} {
  if {$::cluster::config(debug)} {
    puts [list $::cluster::local_pid SEND $args]
  }
  variable discovery_port
  listen
  while {[catch {
    foreach net [::nettool::broadcast_list] {
      if {$::cluster::config(debug)} {
        puts [list BROADCAST -> $net $args]
      }
      set s [udp_open]
      udp_conf $s $net $discovery_port
      chan puts -nonewline $s [list [pid] {*}$args]
      chan flush $s
      chan close $s
    }
  } error]} {
    set ::cluster::broadcast_sock {}
    if {$::cluster::config(debug)} {
      puts "Broadcast ERR: $error - Reopening Socket"
      ::cron::sleep 2000
    } else {
      # Double the delay
      ::cron::sleep 250
    }
  }
}

###
# topic: 963e24601d0dc61580c9727a74cdba67
###
proc ::cluster::cname rawname {
  # Convert rawname to a canonical name
  if {[string first @ $rawname] < 0 } {
    return $rawname
  }
  lassign [split $rawname @] service host
  if {$host eq {}} {
    set host *
  }
  if {$host in {local localhost}} {
    set host [::cluster::self]
  }
  return $service@$host
}

proc ::cluster::Directory args {
  # Fullfill locally
  switch [lindex $args 0] {
    alloc_port {
      return [Get_free_port [lindex $args 1]]
    }
    port_busy {
      return [::nettool::port_busy [lindex $args 1]]
    }
    pid {
      return [pid]
    }
  }
  error "UNKNOWN COMMAND [lindex $args 0]"
}


proc ::cluster::directory args {
  ::cluster::listen
  variable directory_sock
  if {$directory_sock ne {}} {
    return [Directory {*}$args]
  }
  # We are not acting as the directory, query who is
  variable directory_port
  set sock [socket localhost $directory_port]
  chan configure $sock -translation crlf -buffering line -blocking 1
  chan puts $sock $args
  chan flush $sock
  update
  set reply {}
  while {[chan gets $sock line]>0} {
    append reply \n $line
    if {[::info complete $reply]} break
  }
  catch {chan close $sock}
  lassign $reply result errdat
  return $result {*}$errdat
}

###
# topic: 3f5f9e197cc9666dd7953d97fef34019
###
proc ::cluster::ipaddr macid {
  # Convert rawname to a canonical name
  if {$macid eq [::cluster::self]} {
    return 127.0.0.1
  }
  foreach {servname dat} [search [cname *@$macid]] {
    if {[dict exists $dat ipaddr]} {
      return [dict get $dat ipaddr]
    }
  }
  ###
  # Do a lookup
  ###
  error "Could not locate $macid"
}

###
# topic: e57db306f0e931d7febb5ad1f9cb2247
###
proc ::cluster::listen {} {
  variable broadcast_sock
  if {$broadcast_sock != {}} {
    return $broadcast_sock
  }

  variable discovery_port
  # Open a local discovery port to catch non-IP traffic
  variable discovery_group
  set broadcast_sock [udp_open $discovery_port reuse]
  fconfigure $broadcast_sock -buffering none -blocking 0 \
    -broadcast 1 \
    -mcastadd $discovery_group \
    -remote [list $discovery_group $discovery_port]
  chan event $broadcast_sock readable [list [namespace current]::UDPPacket $broadcast_sock]
  ::cron::every cluster_heartbeat 30 ::cluster::heartbeat

  variable directory_sock
  variable directory_pid
  if {$directory_sock eq {} && $directory_pid eq {}} {
    variable directory_port
    # Nobody is acting as the directory. Have this process step on
    if {![catch {socket -server ::cluster::TCPAccept $directory_port} newsock]} {
      set directory_sock $newsock
      set directory_pid [pid]
    } else {
      set directory_sock {}
      set directory_pid {}
    }
  }
  return $broadcast_sock
}

proc ::cluster::sleep args {
  ::cron::sleep {*}$args
}

proc ::cluster::TCPAccept {sock host port} {
  chan configure $sock -translation {crlf crlf} -buffering line -blocking 1
  set packet [chan gets $sock]
  if {![string is ascii $packet]} return
  if {![::info complete $packet]} return
  if {[catch {Directory {*}$packet} reply errdat]} {
    chan puts $sock [list $reply $errdat]
  } else {
    chan puts $sock [list $reply {}]
  }
  chan flush $sock
  chan close $sock
}
###
# topic: 2a33c825920162b0791e2cdae62e6164
###
proc ::cluster::UDPPacket sock {
  variable ptpdata
  set pid [pid]
  set packet [string trim [read $sock]]
  set peer [fconfigure $sock -peer]

  if {![string is ascii $packet]} return
  if {![::info complete $packet]} return

  set sender  [lindex $packet 0]
  if {$::cluster::config(debug)} {
    puts [list $::cluster::local_pid RECV $peer $packet]
  }
  if { $sender eq [pid] } {
    # Ignore messages from myself
    return
  }
  set ipaddr [lindex $peer 0]
  set messagetype [string toupper [lindex $packet 1]]

  # These two message types are not associated with a service
  switch -- $messagetype {
    DISCOVERY {
      variable config
      ::cluster::heartbeat
      return
    }
    ?WHOIS {
      set wmacid [lindex $messageinfo 0]
      if { $wmacid eq [::cluster::self] } {
        broadcast +WHOIS [::cluster::self]
      }
      return
    }
  }

  set now [clock seconds]
  set serviceurl  [lindex $packet 2]
  set serviceinfo [lindex $packet 3]
  set ::cluster::ping_recv($serviceurl) $now
  UDPPortInfo $serviceurl $messagetype $serviceinfo

  if {[dict exists $serviceinfo pid] && [dict get $serviceinfo pid] eq [pid] } {
    # Ignore attempts to overwrite locally managed services from the network
    return
  }
  # Always update the IP of the service info
  dict set ptpdata($serviceurl) ipaddr $ipaddr
  dict set ptpdata($serviceurl) updated $now
  dict set serviceinfo ipaddr [lindex $peer 0]
  dict set serviceinfo updated $now
  set messageinfo [lrange $packet 4 end]

  switch -- $messagetype {
    -SERVICE {
      if {![::info exists ptpdata($serviceurl)]} {
        set result $serviceinfo
      } else {
        set result [dict merge $ptpdata($serviceurl) $serviceinfo]
      }
      dict set result closed 1
      if {[dict exists $result pid] && [dict get $result pid] eq [pid] } {
        # Ignore attempts to overwrite locally managed services from the network
        return
      }
      set ptpdata($serviceurl) $result
      Service_Remove $serviceurl $result
    }
    PONG -
    ~SERVICE {
      set ::cluster::recv_message 1

      if {[::info exists ptpdata($serviceurl)]} {
        set ptpinfo $ptpdata($serviceurl)
      } else {
        set ptpinfo {}
      }
      set delta {}
      foreach {field value} $serviceinfo {
        if {![dict exists $ptpinfo $field] || [dict get $ptpinfo $field] ne $value} {
          dict set ptpdata($serviceurl) $field $value
          dict set delta $field $value
        }
      }
      dict set ptpdata($serviceurl) closed 0
      Service_Modified $serviceurl $serviceinfo $delta
    }
    +SERVICE {
      set ::cluster::recv_message 1
      # Code to register the presence of a service
      variable ptpdata
      set ptpdata($serviceurl) $serviceinfo
      dict set ptpdata($serviceurl) closed 0
      Service_Add $serviceurl $serviceinfo
    }
    LOG {
      Service_Log $serviceurl $serviceinfo
    }
    PING {
      foreach {url info} [search_local $serviceurl] {
        broadcast PONG $url $info
      }
    }
  }
}

proc ::cluster::UDPPortInfo {serviceurl msgtype newinfo} {
  variable ptpdata
  # We only care about port changes on the local machine
  if {[dict exists $newinfo macid]} {
    set macid [dict get $newinfo macid]
    if {$macid ne [::cluster::self]} {
      return
    }
  } elseif {[::info exists ptpdata($serviceurl)] && [dict exists $ptpdata($serviceurl) macid]} {
    set macid [dict get $ptpdata($serviceurl) macid]
    if {$macid ne [::cluster::self]} {
      return
    }
  } else {
    return
  }
  set newport {}
  set oldport {}
  if {[dict exists $newinfo port]} {
    set newport [dict get $newinfo port]
  }
  if {[::info exists ptpdata($serviceurl)] && [dict exists $ptpdata($serviceurl) port]} {
    set oldport [dict get $ptpdata($serviceurl) port]
  }
  switch -- $msgtype {
    -SERVICE {
      if {$oldport ne {}} {
        ::nettool::release_port $oldport
      }
      if {$newport ne {}} {
        ::nettool::release_port $newport
      }
    }
    default {
      if {$oldport ne {}} {
        ::nettool::release_port $oldport
      }
      if {$newport ne {}} {
        ::nettool::claim_port $newport
      }
    }
  }
}

proc ::cluster::ping {rawname {timeout -1}} {
  set rcpt [cname $rawname]
  variable ptpdata
  set starttime [clock seconds]

  set ::cluster::ping_recv($rcpt) 0
  broadcast PING $rcpt
  update
  if {$timeout <= 0} {
    set timeout $::cluster::config(ping_timeout)
  }
  while 1 {
    if {$::cluster::ping_recv($rcpt)} break
    if {([clock seconds] - $starttime) > $timeout} {
      error "Could not locate $rcpt on the network"
    }
    broadcast PING $rcpt
    ::cron::sleep $::cluster::config(ping_sleep)
  }
  if {[::info exists ptpdata($rcpt)]} {
    return [dict getnull $ptpdata($rcpt) ipaddr]
  }
}

proc ::cluster::publish {url infodict} {
  variable local_data
  dict set infodict macid [self]
  dict set infodict pid [pid]
  set local_data($url) [dict merge $infodict {ipaddr 127.0.0.1}]
  broadcast +SERVICE $url $infodict
}

proc ::cluster::heartbeat {} {
  variable ptpdata
  variable config

  _Winnow
  ###
  # Broadcast the status of our local services
  ###
  variable local_data
  foreach {url info} [array get local_data] {
    broadcast ~SERVICE $url $info
  }
  ###
  # Trigger any cluster events that haven't fired off
  ###
  foreach {eventid info} [array get ::cluster::events] {
    if {$info eq "-1"} {
      unset ::cluster::events($eventid)
    } else {
      lassign $info seconds ms
      if {$seconds < $now} {
        set ::cluster::events($eventid) -1
      }
    }
  }
}

proc ::cluster::info url {
  variable local_data
  return [array get local_data $url]
}

proc ::cluster::unpublish {url infodict} {
  variable local_data
  foreach {field value} $infodict {
    dict set local_data($url) $field $value
  }
  set info [lindex [array get local_data $url] 1]
  broadcast -SERVICE $url $info
  dict set local_data($url) closed 1
}

proc ::cluster::configure {url infodict {send 1}} {
  variable local_data
  if {![::info exists local_data($url)]} return
  dict set local_data($url) closed 0
  foreach {field value} $infodict {
    dict set local_data($url) $field $value
  }
  if {$send} {
    broadcast ~SERVICE $url $local_data($url)
    update
  }
}

proc ::cluster::Get_free_port {{port 50000}} {
  if {$port in {{} 0 -1}} {
    set port 50000
  }
  set conflict 1
  while {$conflict} {
    set conflict 0
    set port [::nettool::find_port $port]
    foreach {url info} [search *@[macid]] {
      if {[dict exists $info port] && [dict get $info port] eq $port} {
        incr port
        set conflict 1
        break
      }
    }
    if {$port >= 65336 } {
      error "All ports consumed"
    }
  }
  ::nettool::claim_port $port
  return $port
}

proc ::cluster::get_free_port {{startport 50000}} {
  return [directory alloc_port $startport]
}

proc ::cluster::log args {
  broadcast LOG {*}$args
}

###
# topic: 2c04e58c7f93798f9a5ed31a7f5779ab
###
proc ::cluster::resolve {rawname} {
  variable ptpdata
  set self [self]
  set rcpt [cname $rawname]
  set ipaddr {}
  if {[::info exists ptpdata($rcpt)] && [dict exists $ptpdata($rcpt) macid] && [dict get $ptpdata($rcpt) macid] eq $self} {
    set ipaddr 127.0.0.1
  } elseif {[::info exists ptpdata($rcpt)] && [dict exists $ptpdata($rcpt) ipaddr] && [dict exists $ptpdata($rcpt) updated]} {
    # Try Pull the info from cache
    set updatetm [dict get $ptpdata($rcpt) updated]
    if {([clock seconds] - $updatetm) < 30} {
      set ipaddr [dict get $ptpdata($rcpt) ipaddr]
    }
  }
  if {$ipaddr eq {}} {
    ping $rcpt
    if {![::info exists ptpdata($rcpt)]} {
      error "Could not locate $rcpt on the network"
    }
    if {[dict exists $ptpdata($rcpt) macid] && [dict get $ptpdata($rcpt) macid] eq $self} {
      set ipaddr 127.0.0.1
    } else {
      if {![dict exists $ptpdata($rcpt) ipaddr]} {
        error "Could not locate $rcpt on the network"
      }
      set ipaddr [dict getnull $ptpdata($rcpt) ipaddr]
      if {$ipaddr eq {}} {
        error "Could not locate $rcpt on the network"
      }
    }
  }
  set port [dict getnull $ptpdata($rcpt) port]
  if {$port eq {}} {
    error "Could not locate $rcpt on the network"
  }
  return [list $port $ipaddr]
}

###
# topic: 6c7a0a3a8cb2a7ae98ff0dba960c37a7
###
proc ::cluster::pid {} {
  variable local_pid
  return $local_pid
}

proc ::cluster::macid {} {
  variable local_macid
  return $local_macid
}

proc ::cluster::self {} {
  variable local_macid
  return $local_macid
}

###
# topic: f1b71ff12a8ac10373c67ac5d973cd81
###
proc ::cluster::send {service command args} {
  set commid [resolve $service]
  return [::comm::comm send $commid $command {*}$args]
}

proc ::cluster::throw {service command args} {
  if {[catch {resolve $service} commid]} {
    return
  }
  if [catch {::comm::comm send -async $commid $command {*}$args} reply] {
    puts $stderr "ERR: SEND $service $reply"
  }
}

###
# topic: c8475e832c912e962f238c61580b669e
###
proc ::cluster::search pattern {
  _Winnow
  set result {}
  variable ptpdata
  foreach {service dat} [array get ptpdata $pattern] {
    foreach {field value} $dat {
      dict set result $service $field $value
    }
  }

  variable local_data
  foreach {service dat} [array get local_data $pattern] {
    foreach {field value} $dat {
      dict set result $service $field $value
    }
  }
  return $result
}

proc ::cluster::is_local pattern {
  variable local_data
  if {[array exists local_data $pattern]} {
    return 1
  }
  if {[array exists local_data [cname $pattern]]} {
    return 1
  }
  return 0
}

proc ::cluster::search_local pattern {
  set result {}
  variable local_data
  foreach {service dat} [array get local_data $pattern] {
    foreach {field value} $dat {
      dict set result $service $field $value
    }
  }
  return $result
}

proc ::cluster::Service_Add {serviceurl serviceinfo} {
  # Code to register the emergencs of a new service
}

proc ::cluster::Service_Remove {serviceurl serviceinfo} {
  # Code to register the loss of a service
}

proc ::cluster::Service_Modified {serviceurl serviceinfo {delta {}}} {
  # Code to register an update to a service
}

proc ::cluster::Service_Log {service data delta} {
  # Code to register an event
}

###
# Clean out closed and expired entries
# Performed immediately before searches
# and heartbeats
###
proc ::cluster::_Winnow {} {
  variable ptpdata
  variable config
  variable local_data

  set now [clock seconds]
  foreach {item info} [array get ptpdata] {
    set remove 0
    if {[dict exists $info closed] && [dict get $info closed]} {
      set remove 1
    }
    if {[dict exists $info updated] && ($now - [dict get $info updated])>$config(discovery_ttl)} {
      set remove 1
    }
    if {$remove} {
      unset ptpdata($item)
    }
  }
  foreach {item info} [array get local_data] {
    set remove 0
    if {[dict exists $info closed] && [dict get $info closed]} {
      set remove 1
    }
    if {$remove} {
      unset local_data($item)
    }
  }
}

###
# topic: d3e48e31cc4baf81395179f4097fee1b
###
namespace eval ::cluster {
  # Number of seconds to "remember" data
  variable config
  array set config {
    debug 0
    discovery_ttl 300
    local_registry 0
    ping_timeout 120
    ping_sleep   250
  }
  variable eventcount 0
  variable cache {}
  variable broadcast_sock {}
  variable directory_sock {}

  variable cache_maxage 500
  variable discovery_port 38573
  variable directory_port 38574
  variable directory_pid {}

  # Currently an unassigned group in the
  # Local Network Control Block (224.0.0/24)
  # See: RFC3692 and http://www.iana.org
  variable discovery_group 224.0.0.200
  variable local_port {}
  variable local_macid [lindex [lsort [::nettool::mac_list]] 0]
  variable local_pid   [::uuid::uuid generate]
}

package provide udpcluster 0.3.3