├── meshsim.gif ├── meshsim.png ├── topologiser ├── add_hs_route.sh ├── clear_hs_routes.sh ├── clear_hs_peer_health.sh ├── set_client_health.sh ├── set_hs_peer_health.sh └── topologiser.py ├── stop_hs.sh ├── get_hs_ip.sh ├── get_hs_mac.sh ├── erikj ├── make_room.sh ├── README.md ├── add_accounts.sh ├── join_room.sh └── send_message.sh ├── stop_clean_all.sh ├── clean_hs.sh ├── set_client_health_host.sh ├── requirements.txt ├── init_client_health_host.sh ├── meshsim_orig.py ├── meshsim_nx.py ├── meshsim_nx_four_aerials.py ├── start_hs.sh ├── README.md ├── index.html ├── meshsim.py └── LICENSE /meshsim.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/matrix-org/meshsim/HEAD/meshsim.gif -------------------------------------------------------------------------------- /meshsim.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/matrix-org/meshsim/HEAD/meshsim.png -------------------------------------------------------------------------------- /topologiser/add_hs_route.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | DST=$1 4 | VIA=$2 5 | 6 | ip ro add $VIA dev eth0 7 | ip ro add $DST via $VIA 8 | -------------------------------------------------------------------------------- /stop_hs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | HSID=$1 4 | 5 | #docker stop dendrite$HSID 6 | 7 | docker stop -t 0 synapse$HSID 8 | docker rm synapse$HSID -------------------------------------------------------------------------------- /get_hs_ip.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | HSID=$1 4 | 5 | docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' synapse$HSID 6 | -------------------------------------------------------------------------------- /get_hs_mac.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | HSID=$1 4 | 5 | docker inspect -f '{{range .NetworkSettings.Networks}}{{.MacAddress}}{{end}}' synapse$HSID 6 | -------------------------------------------------------------------------------- /erikj/make_room.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | curl -XPOST "http://localhost:18000/_matrix/client/r0/createRoom?access_token=fake_token" -d '{"preset":"public_chat", "room_alias_name": "test"}' 4 | -------------------------------------------------------------------------------- /erikj/README.md: -------------------------------------------------------------------------------- 1 | 2 | ``` 3 | ./add_accounts $NUM_SERVERS 4 | ./make_room.sh 5 | ./join_room.sh $NUM_SERVERS 6 | ``` 7 | 8 | You might need to run them multiple times if "unrecognized access tokens" come up 9 | -------------------------------------------------------------------------------- /stop_clean_all.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | ids=`docker container ls -f name=synapse -q -a` 4 | 5 | if [[ ! -z $ids ]] 6 | then 7 | echo "stopping $ids" 8 | docker stop -t 0 $ids 9 | docker rm $ids 10 | fi -------------------------------------------------------------------------------- /topologiser/clear_hs_routes.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | GW=`cat /tmp/gw` 4 | NETWORK=${GW/%0.1/0.0} 5 | 6 | # if experimenting with tiny MTU: 7 | #ip link set dev eth0 mtu 150 8 | 9 | ip ro flush all 10 | ip ro add $GW dev eth0 11 | ip ro add blackhole $NETWORK/16 12 | ip ro add default via $GW 13 | -------------------------------------------------------------------------------- /clean_hs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | HSID=$1 4 | 5 | # for db in account device mediaapi syncapi roomserver serverkey federationsender publicroomsapi appservice naffka; do 6 | # dropdb dendrite${HSID}_$db 7 | # done 8 | 9 | # docker rm dendrite$HSID 10 | 11 | dropdb synapse${HSID} 12 | docker rm synapse$HSID -------------------------------------------------------------------------------- /erikj/add_accounts.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | END=$1 4 | 5 | # the default password is 'secret' 6 | password_hash='$2b$12$sN0ba4CTkf0Z5n2OVdGekuEt1cJreZljx2AYFZQCBNhAMwpSXhIwK' 7 | 8 | for i in $(seq 0 $END); do 9 | psql synapse$i <<<"insert into access_tokens(id, user_id, token) values (123123, '@matthew:synapse$i', 'fake_token');"; 10 | done 11 | -------------------------------------------------------------------------------- /erikj/join_room.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | END=$1 4 | 5 | function join { 6 | port=$1 7 | res=$(curl "http://localhost:$port/_matrix/client/r0/join/%23test:synapse0?access_token=fake_token" -XPOST -s) 8 | echo "Result from $port: $res" 9 | } 10 | 11 | for i in $(seq 0 $END); do 12 | port=$(expr 18000 + $i) 13 | join $port 14 | # sleep 2 15 | done 16 | 17 | wait 18 | -------------------------------------------------------------------------------- /set_client_health_host.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | SRCPORT=$1 4 | BW=$2 5 | DELAY=$3 6 | JITTER=$4 7 | 8 | # n.b. srcport & jitter not supported yet 9 | 10 | # On Docker-for-mac we can't do ingress traffic shaping in the linux containers 11 | # as the linux host VM has no IFB module and we don't want to waste our lives 12 | # compiling it. 13 | # 14 | # So instead we shape the traffic on the ingress. 15 | 16 | if [[ `uname` != Darwin ]] 17 | then 18 | exit 19 | fi 20 | 21 | sudo dnctl pipe 1 config bw ${BW}bits/s delay $DELAY -------------------------------------------------------------------------------- /topologiser/clear_hs_peer_health.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | NUM_FLOWS=$1 4 | 5 | GW=`cat /tmp/gw` 6 | 7 | tc qdisc del dev eth0 root 8 | 9 | # we have to set an explicit priomap when bands != 3 10 | # this PRIO is just used to define children for the root, not for prioritising traffic. 11 | tc qdisc add dev eth0 root handle 1: prio bands $NUM_FLOWS priomap 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 12 | 13 | # set the default queue for talking to the host 14 | tc qdisc add dev eth0 parent 1:1 handle 10: sfq 15 | 16 | # filter default traffic to that queue. 17 | tc filter add dev eth0 protocol ip parent 1: \ 18 | u32 match ip dst $GW \ 19 | flowid 1:1 20 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aiofiles==0.4.0 2 | aiohttp==3.5.4 3 | async-timeout==3.0.1 4 | attrs==19.1.0 5 | blinker==1.4 6 | chardet==3.0.4 7 | Click==7.0 8 | decorator==4.4.0 9 | entrypoints==0.3 10 | Flask==1.1.1 11 | h11==0.9.0 12 | h2==3.1.0 13 | hpack==3.0.0 14 | Hypercorn==0.7.0 15 | hyperframe==5.2.0 16 | idna==2.8 17 | itsdangerous==1.1.0 18 | Jinja2==2.10.1 19 | MarkupSafe==1.1.1 20 | mccabe==0.6.1 21 | multidict==4.5.2 22 | networkx==2.3 23 | pkg-resources==0.0.0 24 | pycodestyle==2.5.0 25 | pyflakes==2.1.1 26 | pytoml==0.1.20 27 | Quart==0.9.1 28 | six==1.12.0 29 | sortedcontainers==2.1.0 30 | tenacity==5.0.4 31 | toml==0.10.0 32 | typing-extensions==3.7.4 33 | Werkzeug==0.15.4 34 | wsproto==0.14.1 35 | yarl==1.3.0 36 | -------------------------------------------------------------------------------- /erikj/send_message.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | END=$1 4 | MESSAGE=$2 5 | 6 | function send_message { 7 | id=$1 8 | port=$(expr 18000 + $id) 9 | room_id=$2 10 | res=$(curl "http://localhost:$port/_matrix/client/r0/rooms/$room_id/send/m.room.message?access_token=fake_token" -XPOST -s -d'{"body":"test from '$port': '"$MESSAGE"'", "msgtype":"m.text"}') 11 | echo "Result from $id: $res" 12 | } 13 | 14 | res=$(curl "http://localhost:18000/_matrix/client/r0/join/%23test:synapse0?access_token=fake_token" -XPOST -s) 15 | res=$(echo $res | tr '\n' ' ') 16 | room_id=$(echo $res | jq -r '.room_id') 17 | 18 | for i in $(seq 0 $END); do 19 | send_message $i $room_id 20 | # sleep 2 21 | done 22 | 23 | wait 24 | -------------------------------------------------------------------------------- /init_client_health_host.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [[ `uname` != Darwin ]] 4 | then 5 | exit 6 | fi 7 | 8 | # inspired by https://gist.github.com/dreness/20d7ae82df3997be5d47 9 | 10 | # needs in sudoers: 11 | # 12 | # matthew ALL = (root) NOPASSWD: /usr/sbin/dnctl 13 | # matthew ALL = (root) NOPASSWD: /sbin/pfctl 14 | 15 | # Reset dummynet to default config 16 | sudo dnctl -f flush 17 | 18 | # Compose an addendum to the default config to create a new anchor and table file 19 | read -d '' -r PF <. 19 | 20 | import json 21 | from random import randint 22 | from math import sqrt 23 | from dijkstar import Graph, find_path 24 | 25 | class Server: 26 | _id = 0 27 | 28 | def __init__(self): 29 | self.x = randint(0, 1000) 30 | self.y = randint(0, 1000) 31 | self.id = Server._id 32 | Server._id = Server._id + 1 33 | 34 | self.neighbours = [] 35 | 36 | def distance(self, server): 37 | return sqrt((server.x - self.x)**2 + (server.y - self.y)**2) 38 | 39 | def connect(self, server): 40 | self.neighbours.append(server) 41 | 42 | 43 | MAX_SERVERS = 200 44 | 45 | 46 | def main(): 47 | servers = [] 48 | for i in range(0, MAX_SERVERS): 49 | servers.append(Server()) 50 | 51 | graph = Graph() 52 | 53 | for i in range(0, MAX_SERVERS): 54 | for j in range(i+1, MAX_SERVERS): 55 | distance = servers[i].distance(servers[j]); 56 | if distance < 100: 57 | servers[i].connect(servers[j]) 58 | graph.add_edge(i, j, {'cost': distance}) 59 | 60 | data = { 61 | 'nodes': [], 62 | 'links': [], 63 | } 64 | 65 | for server in servers: 66 | data['nodes'].append({ 67 | 'name': server.id, 68 | 'x': server.x, 69 | 'y': server.y, 70 | }) 71 | for neighbour in server.neighbours: 72 | data['links'].append({ 73 | 'source': server.id, 74 | 'target': neighbour.id, 75 | }) 76 | 77 | # cost_func = lambda u, v, e, prev_e: e['cost'] 78 | # for i in range(0, MAX_SERVERS): 79 | # for j in range(i+1, MAX_SERVERS): 80 | # path = find_path(graph, i, j, cost_func=cost_func) 81 | # data['costs'][i][j] 82 | 83 | print json.dumps(data, sort_keys=True, indent=4) 84 | 85 | main() -------------------------------------------------------------------------------- /meshsim_nx.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright 2019 New Vector Ltd 4 | # 5 | # This file is part of meshsim. 6 | # 7 | # meshsim is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # meshsim is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with coap-proxy. If not, see . 19 | 20 | import json 21 | from random import randint 22 | from math import sqrt 23 | import networkx as nx 24 | 25 | class Server: 26 | _id = 0 27 | 28 | def __init__(self): 29 | self.x = randint(0, 1000) 30 | self.y = randint(0, 1000) 31 | self.id = Server._id 32 | Server._id = Server._id + 1 33 | 34 | self.neighbours = [] 35 | 36 | def distance(self, server): 37 | return sqrt((server.x - self.x)**2 + (server.y - self.y)**2) 38 | 39 | def connect(self, server): 40 | self.neighbours.append(server) 41 | 42 | 43 | MAX_SERVERS = 200 44 | 45 | 46 | def main(): 47 | graph = nx.Graph() 48 | 49 | servers = [] 50 | for i in range(0, MAX_SERVERS): 51 | server = Server() 52 | servers.append(server) 53 | graph.add_node(server.id) 54 | 55 | for i in range(0, MAX_SERVERS): 56 | for j in range(i+1, MAX_SERVERS): 57 | distance = servers[i].distance(servers[j]); 58 | if distance < 100: 59 | servers[i].connect(servers[j]) 60 | graph.add_edge(i, j, weight=distance) 61 | 62 | paths = nx.shortest_path(graph, weight='weight') 63 | costs = nx.shortest_path_length(graph, weight='weight') 64 | 65 | data = { 66 | 'nodes': [], 67 | 'links': [], 68 | 'costs': list(costs), 69 | 'paths': { 70 | u: { 71 | v: paths[u][v][1] if len(paths[u][v])>1 else None 72 | for v in paths[u].keys() 73 | } for u in paths.keys() 74 | }, 75 | } 76 | 77 | for server in servers: 78 | data['nodes'].append({ 79 | 'name': server.id, 80 | 'x': server.x, 81 | 'y': server.y, 82 | }) 83 | for neighbour in server.neighbours: 84 | data['links'].append({ 85 | 'source': server.id, 86 | 'target': neighbour.id, 87 | }) 88 | 89 | print json.dumps(data, sort_keys=True, indent=4) 90 | 91 | main() -------------------------------------------------------------------------------- /meshsim_nx_four_aerials.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright 2019 New Vector Ltd 4 | # 5 | # This file is part of meshsim. 6 | # 7 | # meshsim is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # meshsim is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with coap-proxy. If not, see . 19 | 20 | import json 21 | from random import randint 22 | from math import sqrt 23 | import networkx as nx 24 | 25 | class Server: 26 | _id = 0 27 | 28 | def __init__(self): 29 | self.x = randint(0, 1000) 30 | self.y = randint(0, 1000) 31 | self.id = Server._id 32 | Server._id = Server._id + 1 33 | 34 | self.neighbours = [] 35 | 36 | def distance(self, server): 37 | return sqrt((server.x - self.x)**2 + (server.y - self.y)**2) 38 | 39 | def connect(self, server, limit=None): 40 | if (limit and (len(self.neighbours) > limit or len(server.neighbours) > limit)): 41 | return False 42 | self.neighbours.append(server) 43 | server.neighbours.append(self) 44 | return True 45 | 46 | def reset_neighbours(self): 47 | self.neighbours = [] 48 | 49 | MAX_SERVERS = 200 50 | 51 | 52 | def main(): 53 | graph = nx.Graph() 54 | 55 | servers = [] 56 | for i in range(0, MAX_SERVERS): 57 | server = Server() 58 | servers.append(server) 59 | graph.add_node(server.id) 60 | 61 | # first we wire anyone closer together than 200 62 | for i in range(0, MAX_SERVERS): 63 | for j in range(i+1, MAX_SERVERS): 64 | distance = servers[i].distance(servers[j]); 65 | if distance < 200: 66 | servers[i].connect(servers[j]) 67 | 68 | # then we reset the wirings and rewire the closest 4 neighbours. 69 | # we do this in two phases as we need to have all the possible 70 | # neighbours in place from both 'i' and 'j' sides of the matrix before 71 | # we know which are actually closest. 72 | for i in range(0, MAX_SERVERS): 73 | server = servers[i] 74 | neighbours = { n.id: server.distance(n) for n in server.neighbours } 75 | server.reset_neighbours() 76 | for (j, distance) in sorted(neighbours.items(), key=lambda x: x[1])[0:4]: 77 | if servers[i].connect(servers[j], 4): 78 | graph.add_edge(i, j, weight=distance) 79 | 80 | paths = nx.shortest_path(graph, weight='weight') 81 | costs = nx.shortest_path_length(graph, weight='weight') 82 | 83 | data = { 84 | 'nodes': [], 85 | 'links': [], 86 | 'costs': list(costs), 87 | 'paths': { 88 | u: { 89 | v: paths[u][v][1] if len(paths[u][v])>1 else None 90 | for v in paths[u].keys() 91 | } for u in paths.keys() 92 | }, 93 | } 94 | 95 | for server in servers: 96 | data['nodes'].append({ 97 | 'name': server.id, 98 | 'x': server.x, 99 | 'y': server.y, 100 | }) 101 | for neighbour in server.neighbours: 102 | data['links'].append({ 103 | 'source': server.id, 104 | 'target': neighbour.id, 105 | }) 106 | 107 | print(json.dumps(data, sort_keys=True, indent=4)) 108 | 109 | main() 110 | -------------------------------------------------------------------------------- /topologiser/set_hs_peer_health.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | # Copyright 2019 New Vector Ltd 4 | # 5 | # This file is part of meshsim. 6 | # 7 | # meshsim is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # meshsim is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with coap-proxy. If not, see . 19 | 20 | PEERID=$1 21 | M0=$2; M1=$3; M2=$4; M3=$5; M4=$6; M5=$7 22 | BW=$8 23 | DELAY=$9 24 | JITTER=${10} 25 | 26 | # root 1: prio 27 | # /|\ 28 | # / | \ 29 | # / | \ 30 | # / | \ 31 | # 1:1 1:2 1:3 32 | # | | | 33 | # 10: 20: 30: 34 | # sfq tbf tbf 35 | # | | 36 | # 20:1 30:1 37 | # | | 38 | # 21: 31: 39 | # delay delay 40 | # | | 41 | 42 | 43 | # our packets look like: 44 | # # tcpdump -i eth0 -vvve -xx -XX -n 45 | # 14:19:49.061214 02:42:ac:12:00:02 > 02:42:ac:12:00:03, ethertype IPv4 (0x0800), length 42: (tos 0x0, ttl 64, id 53241, offset 0, flags [DF], proto ICMP (1), length 28) 46 | # 172.18.0.2 > 172.18.0.3: ICMP echo request, id 179, seq 1, length 8 47 | # 0x0000: 0242 ac12 0003 0242 ac12 0002 0800 4500 .B.....B......E. 48 | # 0x0010: 001c cff9 4000 4001 12be ac12 0002 ac12 ....@.@......... 49 | # 0x0020: 0003 0800 f74b 00b3 0001 .....K.... 50 | 51 | # so to filter on destination MAC: 52 | 53 | # 0x0000: 0242 ac12 0003 0800 54 | 55 | # sample data: 56 | # M0=02; M1=42; M2=ac; M3=12; M4=00; M5=03 57 | # BW=300 58 | # DELAY=100 59 | # JITTER=10 60 | 61 | # burst is the number of bytes that we're allowed to send rapidly before the rate limiting 62 | # kicks in (which then compensates to even things out to hit the target rate). 63 | # it has to be > rate limit/scheduler hz (which is easy, given we're on zero HZ sched). 64 | # it also has to be bigger than MTU, otherwise we'll never gather enough tokens in our bucket to 65 | # be able to send a packet. 66 | # 67 | # limit is the maximum size of packets (in bytes) which we allow to stack up before buffering. 68 | # this is converted to latency (in ms) when viewed by `tc -s disc show` 69 | # e.g. a limit of 3000 bytes == (rate/8 * latency) + burst. 70 | # e.g. (256144/8 * 0.0437) + 1600 = 3000 in the example below: 71 | # 72 | # qdisc tbf 30: dev eth0 parent 1:3 rate 256144bit burst 1599b lat 43.7ms 73 | 74 | # we deliberately set the burst rate to be as low as possible - i.e. the MTU (1500 bytes) to smooth 75 | # the bitrate as much as possible. this may overly cripple fast transfers as the token bucket can't 76 | # fill up fast enough but hopefully it'll be okay as our sched is zero hertz. 77 | # It might result in way too many interrupts though. 78 | # 79 | # we deliberately pick MTU + 14 (MAC headers) + 1 to avoid rounding errors 80 | BURST=$((`cat /sys/class/net/eth0/mtu` + 14 + 1)) 81 | 82 | # N.B. we have to pick a tiny MTU as at a 300bps link, 1514 bytes takes 40s to transfer. 83 | # Ideall we would pick an MTU of 150 (so 14 bytes of MAC, 20 IP, 8 UDP + 106 bytes of payload.) 84 | # otherwise we're going to always get 40s for free where everything works fine before suddenly the 85 | # rate limiting kicks in. It might be better to just have a better TC module... 86 | 87 | tc qdisc add dev eth0 parent 1:$PEERID handle ${PEERID}0: tbf rate ${BW}bit burst $BURST limit 10000 88 | tc qdisc add dev eth0 parent ${PEERID}0:1 handle ${PEERID}1: netem delay ${DELAY}ms ${JITTER}ms 25% 89 | 90 | tc filter add dev eth0 protocol ip parent 1: \ 91 | u32 match u16 0x0800 0xFFFF at -2 \ 92 | match u32 0x$M2$M3$M4$M5 0xFFFFFFFF at -12 \ 93 | match u16 0x$M0$M1 0xFFFF at -14 \ 94 | flowid 1:$PEERID 95 | 96 | # to diagnose: 97 | # 98 | # tc qdisc show dev eth0 99 | # tc -s qdisc show dev eth0 100 | # tc filter show dev eth0 101 | 102 | # or if we were doing it by IP: 103 | 104 | #tc filter add dev eth0 protocol ip parent 1:0 prio 3 u32 match ip dst ${PEER}/32 flowid 1:3 105 | -------------------------------------------------------------------------------- /start_hs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2019 New Vector Ltd 4 | # 5 | # This file is part of meshsim. 6 | # 7 | # meshsim is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # meshsim is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with coap-proxy. If not, see . 19 | 20 | if [ "$#" -ne 2 ] 21 | then 22 | echo 'Usage: ./start_hs.sh ' 23 | exit 1 24 | fi 25 | 26 | set -x 27 | 28 | HSID=$1 29 | HOST_IP=$2 30 | 31 | 32 | # for db in account device mediaapi syncapi roomserver serverkey federationsender publicroomsapi appservice naffka; do 33 | # createdb -O dendrite dendrite${HSID}_$db 34 | # done 35 | 36 | # # make sure that you have a monolith image built as: 37 | # # docker build -t monolith . 38 | # # using our custom Dockerfile for dendrite (n.b. *not* docker-compose.yml, as we use a local postgres) 39 | 40 | # if [[ ! -z `docker container ls -f name=synapse${HSID} -q -a` ]] 41 | # then 42 | # # reuse existing container 43 | # exit 44 | # fi 45 | 46 | # docker run -d --name dendrite$HSID -e HSID monolith 47 | 48 | if ! dropdb --if-exists synapse${HSID} ; then 49 | echo "Failed to drop database, bailing" 50 | exit 1 51 | fi 52 | 53 | psql --variable="ON_ERROR_STOP=" -f synapse_template.sql > /dev/null 2>&1 54 | createdb -O synapse synapse${HSID} -T synapse_template 55 | 56 | # shouldn't we put this in the template? 57 | psql synapse$HSID < /sys/kernel/mm/ksm/run 78 | # echo 10000 > /sys/kernel/mm/ksm/pages_to_scan # 40MB of pages at a time 79 | # grep -H '' /sys/kernel/mm/ksm/run/* 80 | # 81 | # N.B. if (and only if) we're playing around with MTU, will need something like: 82 | # ip link set dev br-757a634a355d mtu 150 83 | # ...or whatever our bridge is, as PMTU doesn't seem to be working 84 | # and otherwise we'll get locked out of the guest. 85 | 86 | docker run -d --name synapse$HSID \ 87 | --privileged \ 88 | --network mesh \ 89 | --hostname synapse$HSID \ 90 | -e SYNAPSE_SERVER_NAME=synapse${HSID} \ 91 | -e SYNAPSE_REPORT_STATS=no \ 92 | -e SYNAPSE_ENABLE_REGISTRATION=yes \ 93 | -e SYNAPSE_LOG_LEVEL=INFO \ 94 | -e POSTGRES_DB=synapse$HSID \ 95 | -e POSTGRES_PASSWORD=synapseftw \ 96 | -p $((18000 + HSID)):8008 \ 97 | -p $((19000 + HSID)):3000 \ 98 | -p $((20000 + HSID)):5683/udp \ 99 | -e POSTGRES_HOST=$HOST_IP \ 100 | -e SYNAPSE_LOG_HOST=$HOST_IP \ 101 | -e SYNAPSE_USE_PROXY=1 \ 102 | -e PROXY_DUMP_PAYLOADS=1 \ 103 | synapse 104 | 105 | # or replace the last line for a dummy docker... 106 | # --entrypoint '' \ 107 | # synapse \ 108 | # sleep 365d 109 | 110 | # One can also mount an actual synapse working directory to be able to quickly 111 | # edit synaspe without rebuilding. Simply requires a docker restart after edit... 112 | # --mount type=bind,source=/home/erikj/git/synapse/synapse,destination=/usr/local/lib/python3.7/site-packages/synapse \ 113 | # Similiarly for the coap-proxy: 114 | # --mount type=bind,source=/home/erikj/git/coap-proxy,destination=/proxy 115 | 116 | # to inspect: 117 | # docker run -i -t --entrypoint /bin/bash synapse 118 | -------------------------------------------------------------------------------- /topologiser/topologiser.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright 2019 New Vector Ltd 4 | # 5 | # This file is part of meshsim. 6 | # 7 | # meshsim is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # meshsim is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with coap-proxy. If not, see . 19 | 20 | import os 21 | import sys 22 | import json 23 | from flask import Flask, request, abort, jsonify, send_from_directory 24 | import subprocess 25 | import requests 26 | import psycopg2 27 | 28 | 29 | abspath = os.path.abspath(__file__) 30 | dname = os.path.dirname(abspath) 31 | os.chdir(dname) 32 | 33 | app = Flask(__name__, static_url_path='') 34 | 35 | 36 | if (sys.version_info < (3, 5)): 37 | app.log.error("Needs Python 3.5 or later for subprocess.run()") 38 | exit 39 | 40 | POSTGRES_USER = os.environ.get("POSTGRES_USER", "synapse") 41 | POSTGRES_PASSWORD = os.environ.get("POSTGRES_PASSWORD") 42 | POSTGRES_DB = os.environ.get("POSTGRES_DB", "synapse") 43 | POSTGRES_HOST = os.environ.get("POSTGRES_HOST", "db") 44 | POSTGRES_PORT = os.environ.get("POSTGRES_PORT", 5432) 45 | 46 | 47 | def run(cmd): 48 | out = subprocess.run( 49 | cmd, 50 | capture_output=True, 51 | text=True, 52 | ) 53 | result = "\n>>> " + ' '.join(cmd) 54 | if out.stdout: 55 | result += "\n<<<\n" + out.stdout 56 | if out.stderr: 57 | result += "\n, 98 | # bandwidth: 300, # 300bps 99 | # latency: 200, # 200ms 100 | # jitter: 20, # +/- 20ms - we apply 25% correlation on jitter 101 | # }, ... 102 | # ], 103 | # clients: [ 104 | # { 105 | # source_port: 54312, 106 | # bandwidth: 300, # 300bps 107 | # latency: 200, # 200ms 108 | # jitter: 20, # +/- 20ms - we apply 25% correlation on jitter 109 | # }, ... 110 | # ] 111 | # } 112 | json = request.get_json() 113 | 114 | i = 2 # we start adding the queues from 1:2, as 1:1 is the default queue 115 | flow_count = len(json['peers']) + len(json['clients']) + 1 116 | if flow_count < 2: 117 | flow_count = 2 118 | 119 | result = '' 120 | result += run( 121 | ["./clear_hs_peer_health.sh", str(flow_count)] 122 | ) 123 | for peer in json['peers']: 124 | mac = peer['peer']['mac'].split(":") 125 | result += run( 126 | ["./set_hs_peer_health.sh", str(i)] + 127 | mac + 128 | [str(peer['bandwidth']), str(peer['latency']), str(peer['jitter'])] 129 | ) 130 | i = i + 1 131 | 132 | for client in json['clients']: 133 | result += run( 134 | ["./set_client_health.sh", str(i), str(client.get('source_port', 0))] + 135 | [str(client['bandwidth']), str(client['latency']), str(client['jitter'])] 136 | ) 137 | 138 | return result 139 | 140 | def write_destination_health(dest_to_cost): 141 | conn = psycopg2.connect( 142 | database=POSTGRES_DB, 143 | user=POSTGRES_USER, 144 | password=POSTGRES_PASSWORD, 145 | host=POSTGRES_HOST, 146 | port=POSTGRES_PORT, 147 | ) 148 | with conn: 149 | with conn.cursor() as txn: 150 | txn.execute("TRUNCATE destination_health") 151 | for destination, cost in dest_to_cost.items(): 152 | txn.execute( 153 | "INSERT INTO destination_health VALUES (%s, %s)", 154 | (destination, cost), 155 | ) 156 | 157 | try: 158 | requests.get("http://localhost:8008/_matrix/client/r0/admin/server_health") 159 | except Exception as e: 160 | pass 161 | 162 | app.run(host="0.0.0.0", port=3000, debug=True) 163 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### Simulates a mesh of homeservers with Docker. 2 | 3 | ![meshsim](meshsim.gif) 4 | 5 | Meshsim lets you define and manage an arbitrary network of Matrix homeservers 6 | in docker containers via a web interface. Servers are instantiated by clicking 7 | on the canvas, and the network topology and latency may be adjusted by dragging 8 | servers around. Servers connect to the nearest 5 nodes within the given latency 9 | threshold. 10 | 11 | The bandwidth and latency of individual network links can be overridden by clicking 12 | on the link (which will turn red) and adjusting the specific values. 13 | 14 | Traffic on the network is visualised in realtime by having servers 15 | emit telemetry to the simulator via websocket, showing which events are emitted 16 | and received from which server via which network link. Events are shown as 17 | animated circles which follow the network links between servers. When a server 18 | processes an inbound event, it shows an animation of the event expanding and popping 19 | like a bubble. 20 | 21 | The default docker image that meshsim launches is https://github.com/matrix-org/meshsim-docker 22 | which provides both a Synapse and a [coap-proxy](https://github.com/matrix-org/coap-proxy) 23 | for low-bandwidth Matrix transport experimentation. 24 | 25 | Further details can be found in our FOSDEM 2019 talk about meshsim and coap-proxy at: 26 | https://matrix.org/blog/2019/03/12/breaking-the-100bps-barrier-with-matrix-meshsim-coap-proxy/ 27 | 28 | #### Notes 29 | 30 | * Requires a HS with a Dockerfile which lets it be run in a Debianish container to support KSM. 31 | * Uses KSM to share memory between the server containers. 32 | * Uses a local postgres shared across all the servers as their DB for simplicity. 33 | * Uses Flask and NetworkX to model the network topology in python. 34 | * It puppets the dockerized HSes via `docker run` and talking HTTP to a `topologiser` daemon that runs on the container. 35 | * We deliberately use this rather than docker-compose or docker stack/swarm given the meshsim itself is acting as an orchestrator. 36 | * Uses D3 to visualise and control the network topology in browser. 37 | * Manually puppets the routing tables of the servers based on running dijkstra on the network topo 38 | * Manually puppets TC on the servers to cripple bandwidth, latency & jitter as desired. 39 | * Rather than forcing docker to spin up multiple interfaces per host (which would require gutwrenching the docker's network namespaces), we instead cripple bandwidth on egress traffic per upstream router (as identified by its MAC). 40 | 41 | Now usable in general, but may be a bit fiddly to get up and running. 42 | 43 | #### Installation 44 | 45 | * Supported on macOS (with Docker-for-mac 18.06, not 2.0) & Linux 46 | 47 | * Meshsim requires an up-to-date python installation of at least python 3.6 48 | * Check with `python --version` and/or `python3 --version` 49 | * Install python dependencies with `pip install -r requirements.txt` or `pip3 install -r requirements.txt` 50 | 51 | * Install Docker from docker.com (needs API 1.38; API 1.2x is known not to work.). 52 | * Check the API with `docker version`. 53 | * Your OS packages will probably be too old. 54 | 55 | * create a docker network: `docker network create --driver bridge mesh`. Later 56 | we will need to know the gateway IP (so that the images can talk to postgres, 57 | meshsim, etc on the host). On MacOS `host.docker.internal` will work, 58 | otherwise run `docker network inspect mesh` and find the Gateway IP. 59 | 60 | * Install postgres 61 | * `createuser -P synapse` # password synapseftw 62 | * edit postgresql.conf to ensure postgres is listening on an IP that docker 63 | containers will be able to hit. Set `listen_addresses = ',localhost'`, 64 | although that will only work after step "create a docker network". 65 | If you can't find the config file, have a look in `/var/lib/pgsql/data/`. 66 | * edit pg_hba.conf to ensure connections from docker container IPs will be 67 | allowed (e.g. by enabling `trust` for user `synapse`). Example: 68 | 69 | ``` 70 | # Add the following to the end of the file 71 | local all synapse trust 72 | host all all YOUR_DOCKER_HOST_IP/16 trust 73 | ``` 74 | 75 | * Recommended: It's worth making the user you plan to run meshsim a superuser 76 | in postgres, such that commands do not need to be prefixed with `sudo -u postgres`. 77 | You can do so with the following: 78 | 79 | ``` 80 | sudo -u postgres createuser --superuser --no-password user 81 | ``` 82 | 83 | * Optional: Enable KSM on your host so your synapses can deduplicate RAM 84 | as much as possible 85 | 86 | ```sh 87 | screen ~/Library/Containers/com.docker.docker/Data/vms/0/tty # on Docker-for-Mac 88 | echo 1 > /sys/kernel/mm/ksm/run 89 | echo 10000 > /sys/kernel/mm/ksm/pages_to_scan # 40MB of pages at a time 90 | 91 | # check to see if it's working (will only kick in once you start running something which requests KSM, like our KSMified synapse) 92 | grep -H '' /sys/kernel/mm/ksm/run/* 93 | ``` 94 | 95 | * create a empty directory, e.g. `matrix-low-bandwidth` 96 | 97 | * check out meshsim 98 | ``` 99 | matrix-low-bandwidth$ git clone https://github.com/matrix-org/meshsim.git 100 | ``` 101 | 102 | * Build the (KSM-capable) docker image: 103 | * Clone `synapse` repo and checkout the `babolivier/low-bandwidth` branch (inside the `matrix-low-bandwidth` directory) 104 | ``` 105 | matrix-low-bandwidth$ git clone https://github.com/matrix-org/synapse.git 106 | matrix-low-bandwidth$ cd synapse 107 | synapse$ git checkout babolivier/low-bandwidth 108 | ``` 109 | 110 | * Clone the `meshsim-docker` repo (inside the `matrix-low-bandwidth` directory) 111 | ``` 112 | matrix-low-bandwidth$ git clone https://github.com/matrix-org/meshsim-docker.git 113 | ``` 114 | 115 | * Clone the `coap-proxy` repo (inside the `matrix-low-bandwidth` directory) 116 | ``` 117 | matrix-low-bandwidth$ git clone https://github.com/matrix-org/coap-proxy.git 118 | ``` 119 | 120 | * Run `docker build -t synapse -f meshsim-docker/Dockerfile .` from the top of the 121 | `matrix-low-bandwidth` directory (***not*** inside the `synapse` repo) 122 | 123 | * Optionally edit `start_hs.sh` to add bind mount to a local working copy of 124 | synapse. This allows doing synapse dev without having to rebuild images. See 125 | `start_hs.sh` for details. An example of the `docker run` command in `start_hs.sh` is below: 126 | 127 | ``` 128 | docker run -d --name synapse$HSID \ 129 | --privileged \ 130 | --network mesh \ 131 | --hostname synapse$HSID \ 132 | -e SYNAPSE_SERVER_NAME=synapse${HSID} \ 133 | -e SYNAPSE_REPORT_STATS=no \ 134 | -e SYNAPSE_ENABLE_REGISTRATION=yes \ 135 | -e SYNAPSE_LOG_LEVEL=INFO \ 136 | -e POSTGRES_DB=synapse$HSID \ 137 | -e POSTGRES_PASSWORD=synapseftw \ 138 | -p $((18000 + HSID)):8008 \ 139 | -p $((19000 + HSID)):3000 \ 140 | -p $((20000 + HSID)):5683/udp \ 141 | -e POSTGRES_HOST=$HOST_IP \ 142 | -e SYNAPSE_LOG_HOST=$HOST_IP \ 143 | -e SYNAPSE_USE_PROXY=1 \ 144 | -e PROXY_DUMP_PAYLOADS=1 \ 145 | --mount type=bind,source=/home/user/matrix-low-bandwidth/coap-proxy,destination=/proxy \ 146 | --mount type=bind,source=/home/user/matrix-low-bandwidth/synapse/synapse,destination=/usr/local/lib/python3.7/site-packages/synapse \ 147 | synapse 148 | ``` 149 | 150 | * check you can start a synapse via `./start_hs.sh 1 $DOCKER_IP` with DOCEKR_IP being the docker network gateway IP. 151 | * If the template import fails with something about `en_GB`, make sure you have that locale generated. Replacing `en_GB` with `en_US` or whatever your locale is in `synapse_template.sql` is also sufficient. 152 | * check if it's running with `docker stats` 153 | * check the supervisor logs with `docker logs -f synapse1` and that it can talk to your postgres ok 154 | * log into the container to poke around with `docker exec -it synapse1 /bin/bash` 155 | * Actual synapse logs are located at `/var/log/supervisor/synapse*` 156 | 157 | * Check you can connect to its synapse at http://localhost:18001 (ports are 18000 + hsid). 158 | * Requires a Riot running on http on localhost or similar to support CORS to non-https 159 | * Initial user sign up may time out due to trying to connect to Riot-bot. Simply refresh the page and you should get in fine. 160 | * The KSM'd dockerfile autoprovisions an account on the HS called l/p matthew/secret for testing purposes. 161 | * Check that the topologiser is listening at http://localhost:19001 (ports are 19000 + hsid) 162 | * Don't expect to navigate to this URL and see anything more than a 404. As long as *something* is listening at this port, things are set up correctly. 163 | 164 | * shut it down nicely `./stop_clean_all.sh` 165 | 166 | * run meshsim: `./meshsim.py ` where `` is the docker 167 | network IP for the host (c.f. "create a docker network" step). Run 168 | `./meshsim.py -h` for more options. 169 | * connect to meshsim http://localhost:3000 170 | * click to create HSes 171 | * drag to move them around 172 | * => profit 173 | 174 | You can log into the individual synapse containers as `docker exec -it synapse$N /bin/bash` to traceroute, ping 175 | and generally see what see what's going on. 176 | 177 | #### Using the CoAP proxy 178 | 179 | * Build the proxy (see instruction in the [proxy's README](https://github.com/matrix-org/coap-proxy/blob/master/README.md)) 180 | * Run it by telling it to talk to the HS's proxy: 181 | 182 | ```bash 183 | ./bin/coap-proxy --coap-target localhost:20001 # Ports are 20000 + hsid 184 | ``` 185 | 186 | * Make clients talk to http://localhost:8888 187 | * => profit 188 | 189 | #### Limitations 190 | 191 | Client-Server traffic shaping is only currently supported on macOS, as client->server traffic shaping 192 | is currently implemented on the host (client) side. 193 | 194 | #### License 195 | 196 | Copyright 2019 New Vector Ltd 197 | 198 | This file is part of meshsim. 199 | 200 | meshsim is free software: you can redistribute it and/or modify 201 | it under the terms of the GNU General Public License as published by 202 | the Free Software Foundation, either version 3 of the License, or 203 | (at your option) any later version. 204 | 205 | meshsim is distributed in the hope that it will be useful, 206 | but WITHOUT ANY WARRANTY; without even the implied warranty of 207 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 208 | GNU General Public License for more details. 209 | 210 | You should have received a copy of the GNU General Public License 211 | along with meshsim. If not, see . 212 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 21 | 22 | 23 | 24 | 90 | 91 | 92 | 93 |
94 | 95 | 172 |
173 | 174 | 701 | 702 | 703 | 704 | -------------------------------------------------------------------------------- /meshsim.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Copyright 2019 New Vector Ltd 4 | # 5 | # This file is part of meshsim. 6 | # 7 | # meshsim is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # meshsim is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with coap-proxy. If not, see . 19 | 20 | import argparse 21 | import asyncio 22 | import atexit 23 | import json 24 | import os 25 | import subprocess 26 | from contextlib import contextmanager 27 | from itertools import combinations 28 | from logging.config import dictConfig 29 | from math import sqrt 30 | 31 | import aiohttp 32 | import async_timeout 33 | import networkx as nx 34 | from quart import Quart, abort, jsonify, request, send_from_directory, websocket 35 | from tenacity import retry, wait_fixed 36 | 37 | args = None 38 | 39 | dictConfig({"version": 1, "loggers": {"quart.app": {"level": "INFO"}}}) 40 | 41 | app = Quart(__name__) 42 | 43 | 44 | # We need to create this *after* start up so that it binds to correct event loop 45 | event_notif_queue = None 46 | 47 | 48 | @app.before_first_request 49 | def setup(): 50 | global event_notif_queue 51 | event_notif_queue = asyncio.Queue() 52 | 53 | 54 | async def put(url, data): 55 | async with aiohttp.ClientSession() as session, async_timeout.timeout(30): 56 | async with session.put( 57 | url, data=data, headers={"Content-type": "application/json"} 58 | ) as response: 59 | return await response.text() 60 | 61 | 62 | class Server(object): 63 | _id = 0 64 | 65 | def __init__(self, x, y): 66 | self.x = x 67 | self.y = y 68 | self.id = Server._id 69 | self.ip = None 70 | self.mac = None 71 | Server._id = Server._id + 1 72 | 73 | self.paths = None # cache of shortest paths 74 | self.path_costs = None # cache of shortest path costs 75 | 76 | self.neighbours = set() 77 | 78 | def toDict(self): 79 | return {"id": self.id, "ip": self.ip, "mac": self.mac} 80 | 81 | async def start(self): 82 | global args 83 | proc = await asyncio.create_subprocess_exec( 84 | "./start_hs.sh", str(self.id), args.host 85 | ) 86 | code = await proc.wait() 87 | if code != 0: 88 | raise Exception("Failed to start HS") 89 | await self.update_network_info() 90 | 91 | async def update_network_info(self): 92 | proc = await asyncio.create_subprocess_exec( 93 | "./get_hs_ip.sh", str(self.id), stdout=asyncio.subprocess.PIPE 94 | ) 95 | stdout, _ = await proc.communicate() 96 | self.ip = stdout.decode().strip() 97 | 98 | proc = await asyncio.create_subprocess_exec( 99 | "./get_hs_mac.sh", str(self.id), stdout=asyncio.subprocess.PIPE 100 | ) 101 | stdout, _ = await proc.communicate() 102 | self.mac = stdout.decode().strip() 103 | 104 | @retry(wait=wait_fixed(1)) 105 | async def set_routes(self, routes): 106 | # [ 107 | # { 108 | # dst: server, 109 | # via: server 110 | # }, ... 111 | # ] 112 | data = json.dumps(routes, indent=4) 113 | app.logger.info("setting routes for %d: %s", self.id, data) 114 | 115 | r = await put("http://localhost:%d/routes" % (19000 + self.id), data) 116 | 117 | app.logger.info("Set route with result for %d: %s", self.id, r) 118 | 119 | @retry(wait=wait_fixed(1)) 120 | async def set_network_health(self, health): 121 | # { 122 | # peers: [ 123 | # { 124 | # peer: , 125 | # bandwidth: 300, # 300bps 126 | # latency: 200, # 200ms 127 | # jitter: 20, # +/- 20ms - we apply 25% correlation on jitter 128 | # loss: 0, # 0% packet loss 129 | # }, ... 130 | # ], 131 | # clients: [ 132 | # { 133 | # source_port: 54312, 134 | # bandwidth: 300, # 300bps 135 | # latency: 200, # 200ms 136 | # jitter: 20, # +/- 20ms - we apply 25% correlation on jitter 137 | # loss: 0, # 0% packet loss 138 | # }, ... 139 | # ] 140 | # } 141 | data = json.dumps(health, indent=4) 142 | app.logger.info("setting health for %d: %s", self.id, data) 143 | 144 | # only apply client health on the host side once (picking server 0 arbitrarily) 145 | if self.id == 0: 146 | for client in health.get("clients", []): 147 | proc = await asyncio.create_subprocess_exec( 148 | "./set_client_health_host.sh", 149 | str(client["source_port"]), 150 | str(client["bandwidth"]), 151 | str(client["latency"]), 152 | str(client["jitter"]), 153 | stdout=asyncio.subprocess.PIPE, 154 | ) 155 | stdout, _ = await proc.communicate() 156 | app.logger.info( 157 | "with host result for %d: %s", self.id, stdout.decode().strip() 158 | ) 159 | 160 | r = await put("http://localhost:%d/health" % (19000 + self.id), data) 161 | 162 | app.logger.info("with result for %d: %s", self.id, r) 163 | 164 | def stop(self): 165 | subprocess.call(["./stop_hs.sh", str(self.id)]) 166 | 167 | def distance(self, server2): 168 | return sqrt((server2.x - self.x) ** 2 + (server2.y - self.y) ** 2) 169 | 170 | def connect(self, server2, limit=None): 171 | if limit and (len(self.neighbours) > limit or len(server2.neighbours) > limit): 172 | return False 173 | 174 | # app.logger.info("connecting %d to %d", self.id, server2.id) 175 | 176 | self.neighbours.add(server2) 177 | server2.neighbours.add(self) 178 | return True 179 | 180 | def reset_neighbours(self): 181 | # app.logger.info("resetting neighbours for %d", self.id) 182 | self.neighbours = set() 183 | 184 | 185 | class Mesh: 186 | 187 | COST_MIN_LATENCY = "cost_min_latency" 188 | COST_MAX_BANDWIDTH = "cost_max_bandwidth" 189 | 190 | def __init__(self, host_ip): 191 | self.graph = nx.Graph() 192 | self.servers = {} 193 | 194 | self.rewiring = False 195 | self.pending_rewire = False 196 | 197 | # global defaults 198 | self.bandwidth = 512000 199 | self.decay_bandwidth = True 200 | self.latency_scale = 100 201 | self.max_latency = 300 202 | self.min_bandwidth = 0 203 | self.jitter = 0 204 | self.packet_loss = 0 205 | self.cost_function = Mesh.COST_MIN_LATENCY 206 | 207 | self.client_bandwidth = 512000 208 | self.client_latency = 0 209 | self.client_jitter = 0 210 | self.client_loss = 0 211 | 212 | # link overrides 213 | self.overrides = {} 214 | 215 | # Number of things that are about to call rewire. Don't bother rewiring 216 | # unless this is zero. 217 | self._about_to_rewire_functions = 0 218 | 219 | async def add_server(self, server): 220 | # we deliberately add the server asap so we can echo its existence 221 | # back to the UI. however, we have to deliberately ignore it from 222 | # wiring calculations given it hasn't yet started 223 | self.servers[server.id] = server 224 | self.graph.add_node(server.id) 225 | 226 | with self.will_rewire(): 227 | await server.start() 228 | 229 | await self.safe_rewire() 230 | return server 231 | 232 | def get_server(self, server_id): 233 | return self.servers[server_id] 234 | 235 | async def move_server(self, server, x, y): 236 | server.x = x 237 | server.y = y 238 | await self.safe_rewire() 239 | 240 | async def remove_server(self, server): 241 | server.stop() 242 | self.graph.remove_node(server.id) 243 | 244 | await self.safe_rewire() 245 | 246 | async def safe_rewire(self): 247 | if self._about_to_rewire_functions: 248 | app.logger.info("Skipping rewire as one will be triggered") 249 | return 250 | 251 | if self.rewiring: 252 | # no point in stacking them up 253 | if self.pending_rewire: 254 | app.logger.info( 255 | "Skipping rewire as one already happening and one already queued" 256 | ) 257 | else: 258 | app.logger.info("Deferring rewire as one already happening") 259 | self.pending_rewire = True 260 | return 261 | 262 | self.rewiring = True 263 | 264 | try: 265 | await self._rewire() 266 | finally: 267 | self.rewiring = False 268 | if self.pending_rewire: 269 | self.pending_rewire = False 270 | await self.safe_rewire() 271 | 272 | async def _rewire(self): 273 | if self.cost_function == Mesh.COST_MIN_LATENCY: 274 | cost_function = self.get_latency 275 | elif self.cost_function == Mesh.COST_MAX_BANDWIDTH: 276 | cost_function = self.get_bandwidth_cost 277 | 278 | started_servers = { 279 | i: self.servers[i] for i in self.servers if self.servers[i].ip is not None 280 | } 281 | 282 | # only try to wire servers which have started up and have IPs 283 | for server in started_servers.values(): 284 | # Uncomment if we want to recheck IP/mac addresses of the containers: 285 | # await server.update_network_info() 286 | 287 | server.reset_neighbours() 288 | self.graph.remove_edges_from(list(self.graph.edges())) 289 | 290 | # first we wire anyone closer together than our thresholds 291 | for server1, server2 in combinations(started_servers.values(), 2): 292 | latency = self.get_latency(server1, server2) 293 | bandwidth = self.get_bandwidth(server1, server2) 294 | 295 | if latency < self.max_latency and bandwidth > self.min_bandwidth: 296 | server1.connect(server2) 297 | 298 | # then we reset the wirings and rewire the closest 4 neighbours. 299 | # we do this in two phases as we need to have all the possible 300 | # neighbours in place from both 'i' and 'j' sides of the matrix before 301 | # we know which are actually closest. 302 | for server in started_servers.values(): 303 | neighbour_costs = { 304 | s.id: cost_function(server, s) for s in server.neighbours 305 | } 306 | server.reset_neighbours() 307 | for (j, cost) in sorted(neighbour_costs.items(), key=lambda x: x[1])[0:4]: 308 | if server.connect(started_servers[j], 4): 309 | self.graph.add_edge(server.id, j, weight=cost) 310 | 311 | self.paths = nx.shortest_path(self.graph, weight="weight") 312 | self.path_costs = dict(nx.shortest_path_length(self.graph, weight="weight")) 313 | 314 | # app.logger.info("calculated shortest paths as %r", self.paths) 315 | 316 | c = list(combinations(started_servers, 2)) 317 | app.logger.info("combinations %r", c) 318 | 319 | futures = ( 320 | # apply the network topology in terms of routing table 321 | [ 322 | self.get_server(source_id).set_routes( 323 | [ 324 | { 325 | "dst": self.get_server(dest_id).toDict(), 326 | "via": ( 327 | self.get_server( 328 | self.paths[source_id][dest_id][1] 329 | ).toDict() 330 | if len(self.paths[source_id].get(dest_id, [])) > 1 331 | else None 332 | ), 333 | "cost": self.path_costs[source_id].get(dest_id), 334 | } 335 | for dest_id in started_servers 336 | if source_id != dest_id 337 | ] 338 | ) 339 | for source_id in started_servers 340 | ] 341 | + 342 | # apply the network characteristics to the peers 343 | [ 344 | self.get_server(i).set_network_health( 345 | { 346 | "peers": [ 347 | { 348 | "peer": neighbour.toDict(), 349 | "bandwidth": self.get_bandwidth( 350 | self.get_server(i), neighbour 351 | ), 352 | "latency": self.get_latency( 353 | self.get_server(i), neighbour 354 | ), 355 | "jitter": self.get_jitter( 356 | self.get_server(i), neighbour 357 | ), 358 | "packet_loss": self.get_packet_loss( 359 | self.get_server(i), neighbour 360 | ), 361 | } 362 | for neighbour in self.get_server(i).neighbours 363 | ], 364 | "clients": [ 365 | { 366 | "source_port": 0, # FIXME once we support multiple clients 367 | "bandwidth": self.client_bandwidth, 368 | "latency": self.client_latency, 369 | "jitter": self.client_jitter, 370 | "loss": self.client_loss, 371 | } 372 | ], 373 | } 374 | ) 375 | for i in started_servers 376 | ] 377 | ) 378 | 379 | await asyncio.gather(*futures) 380 | 381 | def get_bandwidth_cost(self, server1, server2): 382 | return 1 / self.get_bandwidth(server1, server2) 383 | 384 | def get_bandwidth(self, server1, server2): 385 | if server1.id > server2.id: 386 | tmp = server1 387 | server1 = server2 388 | server2 = tmp 389 | 390 | override = self.overrides.get(server1.id, {}).get(server2.id, None) 391 | if override and override.get("bandwidth") is not None: 392 | return override.get("bandwidth") 393 | 394 | if self.decay_bandwidth: 395 | distance = server1.distance(server2) 396 | return int( 397 | self.bandwidth 398 | * ((self.max_latency - server1.distance(server2)) / self.max_latency) 399 | ) 400 | else: 401 | return self.bandwidth 402 | 403 | def get_latency(self, server1, server2): 404 | if server1.id > server2.id: 405 | tmp = server1 406 | server1 = server2 407 | server2 = tmp 408 | 409 | override = self.overrides.get(server1.id, {}).get(server2.id, None) 410 | if override and override.get("latency") is not None: 411 | return override["latency"] * (self.latency_scale / 100) 412 | 413 | return int(server1.distance(server2)) * (self.latency_scale / 100) 414 | 415 | def get_jitter(self, server1, server2): 416 | if server1.id > server2.id: 417 | tmp = server1 418 | server1 = server2 419 | server2 = tmp 420 | 421 | override = self.overrides.get(server1.id, {}).get(server2.id, None) 422 | if override and override.get("jitter") is not None: 423 | return override["jitter"] 424 | 425 | return self.jitter 426 | 427 | def get_packet_loss(self, server1, server2): 428 | if server1.id > server2.id: 429 | tmp = server1 430 | server1 = server2 431 | server2 = tmp 432 | 433 | override = self.overrides.get(server1.id, {}).get(server2.id, None) 434 | if override and override.get("packet_loss") is not None: 435 | return override["packet_loss"] 436 | 437 | return self.packet_loss 438 | 439 | def set_link_health(self, server1_id, server2_id, health): 440 | override = {} 441 | for t in ["bandwidth", "latency", "jitter", "packet_loss"]: 442 | if t in health: 443 | override[t] = int(health.get(t)) if health.get(t) is not None else None 444 | 445 | self.overrides.setdefault(server1_id, {}).setdefault(server2_id, {}).update( 446 | override 447 | ) 448 | app.logger.info("link health overrides now %r", self.overrides) 449 | 450 | def get_d3_data(self): 451 | data = {"nodes": [], "links": []} 452 | 453 | # XXX: frontend relies on index in data.nodes matches the server ID 454 | for _, server in sorted(self.servers.items()): 455 | data["nodes"].append({"name": server.id, "x": server.x, "y": server.y}) 456 | for neighbour in server.neighbours: 457 | if server.id < neighbour.id: 458 | link = { 459 | "source": server.id, 460 | "target": neighbour.id, 461 | "bandwidth": self.get_bandwidth(server, neighbour), 462 | "latency": self.get_latency(server, neighbour), 463 | "jitter": self.get_jitter(server, neighbour), 464 | "packet_loss": self.get_packet_loss(server, neighbour), 465 | } 466 | 467 | overrides = self.overrides.get(server.id, {}).get(neighbour.id, {}) 468 | for override in overrides: 469 | if overrides[override] is not None: 470 | link.setdefault("overrides", {})[override] = True 471 | 472 | data["links"].append(link) 473 | 474 | return json.dumps(data, sort_keys=True, indent=4) 475 | 476 | def get_costs(self): 477 | if not self.path_costs: 478 | self.path_costs = dict(nx.shortest_path_length(self.graph, weight="weight")) 479 | return self.paths_costs 480 | 481 | def get_path(self, origin, target): 482 | if not self.paths: 483 | self.paths = nx.shortest_path(self.graph, weight="weight") 484 | return self.paths[origin][target] 485 | 486 | def get_defaults(self): 487 | return { 488 | "bandwidth": self.bandwidth, 489 | "decay_bandwidth": self.decay_bandwidth, 490 | "max_latency": self.max_latency, 491 | "min_bandwidth": self.min_bandwidth, 492 | "jitter": self.jitter, 493 | "packet_loss": self.packet_loss, 494 | "cost_function": self.cost_function, 495 | "latency_scale": self.latency_scale, 496 | "client_latency": self.client_latency, 497 | "client_bandwidth": self.client_bandwidth, 498 | "client_jitter": self.client_jitter, 499 | "client_loss": self.client_loss, 500 | } 501 | 502 | def set_defaults(self, defaults): 503 | self.bandwidth = int(defaults.get("bandwidth", self.bandwidth)) 504 | self.decay_bandwidth = bool( 505 | defaults.get("decay_bandwidth", self.decay_bandwidth) 506 | ) 507 | self.max_latency = int(defaults.get("max_latency", self.max_latency)) 508 | self.min_bandwidth = int(defaults.get("min_bandwidth", self.min_bandwidth)) 509 | self.jitter = int(defaults.get("jitter", self.jitter)) 510 | self.packet_loss = int(defaults.get("packet_loss", self.packet_loss)) 511 | self.cost_function = defaults.get("cost_function", self.cost_function) 512 | self.latency_scale = int(defaults.get("latency_scale", self.jitter)) 513 | self.client_latency = int(defaults.get("client_latency", self.client_latency)) 514 | self.client_bandwidth = int( 515 | defaults.get("client_bandwidth", self.client_bandwidth) 516 | ) 517 | self.client_jitter = int(defaults.get("client_jitter", self.client_jitter)) 518 | self.client_loss = int(defaults.get("client_loss", self.client_loss)) 519 | 520 | @contextmanager 521 | def will_rewire(self): 522 | try: 523 | self._about_to_rewire_functions += 1 524 | yield 525 | finally: 526 | self._about_to_rewire_functions -= 1 527 | 528 | 529 | mesh = Mesh("") 530 | 531 | 532 | @app.route("/") 533 | def send_index(): 534 | return send_from_directory("", "index.html") 535 | 536 | 537 | @app.route("/static/") 538 | def send_static(filename): 539 | return send_from_directory("static/", filename) 540 | 541 | 542 | @app.route("/server", methods=["POST"]) 543 | async def on_add_server(): 544 | # { 545 | # "x": 120, 546 | # "y": 562 547 | # } 548 | incoming_json = await request.get_json() 549 | if not incoming_json: 550 | abort(400, "No JSON provided!") 551 | return 552 | 553 | x = incoming_json.get("x") 554 | y = incoming_json.get("y") 555 | 556 | server = await mesh.add_server(Server(x, y)) 557 | return jsonify({"id": server.id}) 558 | 559 | 560 | @app.route("/server//position", methods=["PUT"]) 561 | async def on_position_server(server_id): 562 | # { 563 | # "x": 120, 564 | # "y": 562 565 | # } 566 | server_id = int(server_id) 567 | incoming_json = await request.get_json() 568 | if not incoming_json: 569 | abort(400, "No JSON provided!") 570 | return 571 | 572 | x = incoming_json.get("x") 573 | y = incoming_json.get("y") 574 | 575 | server = mesh.get_server(server_id) 576 | await mesh.move_server(server, x, y) 577 | 578 | return "" 579 | 580 | 581 | def name_to_id(name): 582 | return int(name.replace("synapse", "")) 583 | 584 | 585 | @app.route("/log", methods=["GET"]) 586 | async def on_incoming_log(): 587 | args = request.args 588 | server = args["server"] 589 | msg = args["msg"] 590 | if msg == "ReceivedPDU": 591 | event_id = args["event_id"] 592 | origin = args["origin"] 593 | app.logger.info(f"Received {event_id}. {origin} -> {server}") 594 | await event_notif_queue.put( 595 | { 596 | "event_type": "receive", 597 | "source": origin, 598 | "target": server, 599 | "event": event_id, 600 | } 601 | ) 602 | elif msg == "SendingPDU": 603 | event_id = args["event_id"] 604 | destinations = json.loads(args["destinations"]) 605 | for destination in destinations: 606 | app.logger.info(f"{server} Sending {event_id}. {server} -> {destination}") 607 | await event_notif_queue.put( 608 | { 609 | "event_type": "sending", 610 | "source": server, 611 | "target": destination, 612 | "path": mesh.get_path(name_to_id(server), name_to_id(destination)), 613 | "event": event_id, 614 | } 615 | ) 616 | return "" 617 | 618 | 619 | @app.websocket("/event_notifs") 620 | async def event_notifs(): 621 | while True: 622 | msg = await event_notif_queue.get() 623 | await websocket.send(json.dumps(msg)) 624 | 625 | 626 | @app.route("/data", methods=["GET"]) 627 | def on_get_data(): 628 | return mesh.get_d3_data() 629 | 630 | 631 | @app.route("/costs", methods=["GET"]) 632 | def on_get_costs(): 633 | return jsonify(mesh.get_costs()) 634 | 635 | 636 | @app.route("/defaults", methods=["GET"]) 637 | def on_get_defaults(): 638 | return jsonify(mesh.get_defaults()) 639 | 640 | 641 | @app.route("/defaults", methods=["PUT"]) 642 | async def on_put_defaults(): 643 | json = await request.get_json() 644 | mesh.set_defaults(json) 645 | await mesh.safe_rewire() 646 | return "" 647 | 648 | 649 | @app.route("/link///", methods=["PUT"]) 650 | async def on_put_link_health(server1, server2, type): 651 | json = await request.get_json() 652 | mesh.set_link_health(int(server1), int(server2), json) 653 | await mesh.safe_rewire() 654 | return "" 655 | 656 | 657 | @app.route("/link///", methods=["DELETE"]) 658 | async def on_delete_link_health(server1, server2, type): 659 | json = {} 660 | json[type] = None 661 | mesh.set_link_health(int(server1), int(server2), json) 662 | await mesh.safe_rewire() 663 | return "" 664 | 665 | 666 | def cleanup(): 667 | subprocess.call(["./stop_clean_all.sh"]) 668 | 669 | 670 | @app.before_first_request 671 | def setup(): 672 | atexit.register(cleanup) 673 | 674 | 675 | def main(): 676 | global args 677 | 678 | parser = argparse.ArgumentParser(description="Synapse network simulator.") 679 | parser.add_argument( 680 | "host", help="The IP address of this host in the docker network." 681 | ) 682 | parser.add_argument( 683 | "--port", 684 | "-p", 685 | help="The port for meshsim to listen on", 686 | nargs=1, 687 | default=3000, 688 | type=int, 689 | ) 690 | parser.add_argument( 691 | "--jaeger", 692 | "-j", 693 | help="Enable Jaeger tracing in Synapse and CoAP proxy", 694 | action="store_true", 695 | ) 696 | parser.add_argument( 697 | "--no-proxy", 698 | "-n", 699 | help="Have Synapse talk directly to each other rather than via the CoAP proxy", 700 | action="store_false", 701 | dest="use_proxy", 702 | ) 703 | parser.add_argument( 704 | "--proxy-dump-payloads", 705 | help="Debug option to make the CoAP proxy log the packets that are being sent/received", 706 | action="store_true", 707 | ) 708 | args = parser.parse_args() 709 | 710 | host = args.host 711 | os.environ["POSTGRES_HOST"] = host 712 | os.environ["SYNAPSE_LOG_HOST"] = host 713 | 714 | if args.jaeger: 715 | os.environ["SYNAPSE_JAEGER_HOST"] = host 716 | 717 | if args.use_proxy: 718 | os.environ["SYNAPSE_USE_PROXY"] = "1" 719 | 720 | if args.proxy_dump_payloads: 721 | os.environ["PROXY_DUMP_PAYLOADS"] = "1" 722 | 723 | subprocess.call(["./init_client_health_host.sh"]) 724 | app.run(host="0.0.0.0", port=args.port, debug=True) 725 | 726 | 727 | if __name__ == "__main__": 728 | main() 729 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------