├── requirements.txt
├── docs
├── _static
│ └── pythorrent.css
├── modules.rst
├── _templates
│ └── layout.html
├── index.rst
├── pythorrent.rst
├── Makefile
└── conf.py
├── .gitignore
├── tests
├── __init__.py
└── test_tracker.py
├── Makefile
├── setup.py
├── pythorrent
├── __init__.py
├── config.py
├── __main__.py
├── pieces.py
├── peer_stores.py
├── torrent.py
└── peer.py
├── README.md
├── README.rst
└── LICENSE
/requirements.txt:
--------------------------------------------------------------------------------
1 | torrentool
2 | requests
3 | bitarray
4 | PyYAML
5 |
--------------------------------------------------------------------------------
/docs/_static/pythorrent.css:
--------------------------------------------------------------------------------
1 | a {
2 | color: #558 !important;
3 | }
4 |
--------------------------------------------------------------------------------
/docs/modules.rst:
--------------------------------------------------------------------------------
1 | PYThorrent
2 | ==========
3 |
4 | .. toctree::
5 | :maxdepth: 4
6 |
7 | pythorrent
8 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *~
2 | *.db
3 | *.log
4 | *.gimmick
5 | test.txt
6 | *.iso
7 | *.torrent
8 | *.pyc
9 | *.egg*
10 | /docs/_build/*
11 | /build/*
12 |
--------------------------------------------------------------------------------
/docs/_templates/layout.html:
--------------------------------------------------------------------------------
1 | {# layout.html #}
2 | {# Import the theme's layout. #}
3 | {% extends "!layout.html" %}
4 |
5 | {% set css_files = css_files + ['_static/pythorrent.css'] %}
6 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | import pythorrent
3 |
4 | def my_module_suite():
5 | loader = unittest.TestLoader()
6 | suite = loader.loadTestsFromModule(test_module)
7 | return suite
8 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | .PHONY: docs
2 |
3 | clean:
4 | find . -name '*.pyc' -delete
5 | find . -name '*.pyo' -delete
6 | find . -name '*~' -delete
7 |
8 | docs:
9 | $(MAKE) -C docs html
10 | pandoc README.md --from markdown --to rst -s -o README.rst
11 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | .. PYThorrent documentation master file, created by
2 | sphinx-quickstart on Mon Jul 25 17:55:13 2016.
3 | You can adapt this file completely to your liking, but it should at least
4 | contain the root `toctree` directive.
5 |
6 | Welcome to PYThorrent's documentation!
7 | ======================================
8 |
9 | Contents:
10 |
11 | .. toctree::
12 | :maxdepth: 2
13 |
14 |
15 | Indices and tables
16 | ==================
17 |
18 | * :ref:`genindex`
19 | * :ref:`modindex`
20 | * :ref:`search`
21 |
22 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 | from os import path
3 |
4 | def read(fname):
5 | return open(path.join(path.dirname(__file__), fname)).read()
6 |
7 | setup(
8 | name='PYTHorrent',
9 | version='0.1',
10 | description="A BitTorrent client written entirely in Python so "\
11 | "that you can get to the depths of the protocol",
12 | long_description=read("README.rst"),
13 | author='Matt Copperwaite',
14 | author_email='mattcopp@gmail.com',
15 | url='https://github.com/yamatt/python-pythorrent',
16 | packages=[
17 | 'pythorrent',
18 | ],
19 | license="AGPLv3",
20 | test_suite="tests",
21 | install_requires=read("requirements.txt").split()
22 | )
23 |
--------------------------------------------------------------------------------
/tests/test_tracker.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from pythorrent.peer_stores import Tracker
3 | from datetime import datetime, timedelta
4 |
5 | class TestTrackerAnnounce(unittest.TestCase):
6 | def setUp(self):
7 | self.tracker = Tracker("", None)
8 | self.now = datetime.utcnow()
9 |
10 | def test_announce_ok_when_not_set(self):
11 | self.tracker.last_run = None
12 | self.assertTrue(self.tracker.ok_to_announce)
13 |
14 | def test_announce_ok_when_last_run_in_past(self):
15 | self.tracker.last_run = self.now - self.tracker.delta
16 | self.assertTrue(self.tracker.ok_to_announce)
17 |
18 | def test_announce_ok_when_last_run_in_future(self):
19 | self.tracker.last_run = self.now + self.tracker.delta
20 | self.assertFalse(self.tracker.ok_to_announce)
21 |
22 |
23 |
--------------------------------------------------------------------------------
/pythorrent/__init__.py:
--------------------------------------------------------------------------------
1 | # This file is part of PYThorrent.
2 | #
3 | # PYThorrent is free software: you can redistribute it and/or modify
4 | # it under the terms of the GNU General Public License as published by
5 | # the Free Software Foundation, either version 3 of the License, or
6 | # (at your option) any later version.
7 | #
8 | # PYThorrent is distributed in the hope that it will be useful,
9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | # GNU General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with PYThorrent. If not, see .
15 |
16 | def splice(s, n):
17 | """Split apart a string at a particular length"""
18 | return [ s[i:i+n] for i in range(0, len(s), n) ]
19 |
20 | class BitTorrentException(Exception):
21 | pass
22 |
--------------------------------------------------------------------------------
/docs/pythorrent.rst:
--------------------------------------------------------------------------------
1 | PYThorrent package
2 | ==================
3 |
4 | Submodules
5 | ----------
6 |
7 | pythorrent.config module
8 | ------------------------
9 |
10 | .. automodule:: pythorrent.config
11 | :members:
12 | :undoc-members:
13 | :show-inheritance:
14 |
15 | pythorrent.peer module
16 | ----------------------
17 |
18 | .. automodule:: pythorrent.peer
19 | :members:
20 | :undoc-members:
21 | :show-inheritance:
22 |
23 | pythorrent.peer_stores module
24 | -----------------------------
25 |
26 | .. automodule:: pythorrent.peer_stores
27 | :members:
28 | :undoc-members:
29 | :show-inheritance:
30 |
31 | pythorrent.pieces module
32 | ------------------------
33 |
34 | .. automodule:: pythorrent.pieces
35 | :members:
36 | :undoc-members:
37 | :show-inheritance:
38 |
39 | pythorrent.torrent module
40 | -------------------------
41 |
42 | .. automodule:: pythorrent.torrent
43 | :members:
44 | :undoc-members:
45 | :show-inheritance:
46 |
47 |
48 | Module contents
49 | ---------------
50 |
51 | .. automodule:: pythorrent
52 | :members:
53 | :undoc-members:
54 | :show-inheritance:
55 |
--------------------------------------------------------------------------------
/pythorrent/config.py:
--------------------------------------------------------------------------------
1 | # This file is part of PYThorrent.
2 | #
3 | # PYThorrent is free software: you can redistribute it and/or modify
4 | # it under the terms of the GNU General Public License as published by
5 | # the Free Software Foundation, either version 3 of the License, or
6 | # (at your option) any later version.
7 | #
8 | # PYThorrent is distributed in the hope that it will be useful,
9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | # GNU General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with PYThorrent. If not, see .
15 |
16 | import yaml
17 |
18 | import logging
19 |
20 | class Config(object):
21 | @classmethod
22 | def from_path(cls, path):
23 | """
24 | """
25 | return cls.from_file(
26 | open(path)
27 | )
28 |
29 | @classmethod
30 | def from_file(cls, f):
31 | """
32 | """
33 | return cls(
34 | yaml.safe_load(f)
35 | )
36 |
37 | def __init__(self, config):
38 | """
39 | """
40 | self._config = config
41 |
42 | def __getitem__(self, key):
43 | """
44 | """
45 | return self._config.get(key)
46 |
47 | def __getattribute__(self, attr):
48 | """
49 | """
50 | return self[attr]
51 |
52 | def load_config(opts):
53 | """
54 | """
55 | return Config.from_path(opts)
56 |
--------------------------------------------------------------------------------
/pythorrent/__main__.py:
--------------------------------------------------------------------------------
1 | # This file is part of PYThorrent.
2 | #
3 | # PYThorrent is free software: you can redistribute it and/or modify
4 | # it under the terms of the GNU General Public License as published by
5 | # the Free Software Foundation, either version 3 of the License, or
6 | # (at your option) any later version.
7 | #
8 | # PYThorrent is distributed in the hope that it will be useful,
9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | # GNU General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with PYThorrent. If not, see .
15 |
16 | from .torrent import Torrent
17 | from .config import load_config
18 |
19 | import logging
20 |
21 | from random import choice
22 |
23 | from optparse import OptionParser
24 |
25 | def get_args():
26 | parser = OptionParser()
27 | parser.add_option("-f", "--file", dest="file",
28 | help="Torrent FILE", metavar="FILE")
29 | parser.add_option("-p", "--path", dest="path",
30 | help="Where to save the torrent output")
31 | parser.add_option("--log", dest="log", help="Log level")
32 |
33 | options, _ = parser.parse_args()
34 |
35 | auto_args(options)
36 |
37 | return options
38 |
39 | def auto_args(options):
40 | """
41 | """
42 | level = getattr(logging, options.log.upper())
43 | logging.basicConfig(level=level)
44 |
45 | if __name__ == "__main__":
46 | options = get_args()
47 | client = Torrent.from_path(options.file, options.path)
48 | client.run()
49 |
50 |
51 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PYTHorrent
2 | This is a BitTorrent client written entirely in Python so that it can be easily used for experiments. It is a fully working BitTorrent client so you can use it below as an example. There is no intelligence in this such as getting rarest peice first. Everything is random.
3 |
4 | It doesn't use `thread` or `multiprocessing` as it's designed to be used for experiments, and I don't know how someone may want to use it, while also making it impractical for general use, but I'd like to eventually support the most common schemes such as DHT, Magnet URLs, PHE tDP, and UPnP so it is possible to accept incoming connections.
5 |
6 | ## Installation
7 | ### PIP
8 |
9 | pip install pythorrent
10 |
11 | ### From Source
12 |
13 | pip install -r requirements.txt
14 | python setup.py install
15 |
16 | ## Usage
17 | Depending on how you installed PYTHorrent you may need to go to the root of the source of the PYTHorrent directory.
18 |
19 | cd python-pythorrent
20 |
21 | ### Getting commands
22 |
23 | python -m pythorrent -h
24 |
25 | ### Downloading a Torrent using a torrent file
26 |
27 | python -m pythorrent --file ubuntu-16.04-desktop-amd64.iso.torrent --path . --log=info
28 |
29 | ## Overview
30 | Documentation for the BitTorrent protocol is poor but these sources have been immensely helpful:
31 |
32 | - http://jonas.nitro.dk/bittorrent/bittorrent-rfc.html
33 | - https://wiki.theory.org/BitTorrentSpecification
34 | - http://www.kristenwidman.com/blog/33/how-to-write-a-bittorrent-client-part-1/
35 | - http://www.kristenwidman.com/blog/71/how-to-write-a-bittorrent-client-part-2/
36 |
37 | ## License
38 | ### AGPLv3
39 |
40 | This program is free software: you can redistribute it and/or modify
41 | it under the terms of the GNU General Public License as published by
42 | the Free Software Foundation, either version 3 of the License, or
43 | (at your option) any later version.
44 |
45 | This program is distributed in the hope that it will be useful,
46 | but WITHOUT ANY WARRANTY; without even the implied warranty of
47 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
48 | GNU General Public License for more details.
49 |
50 | You should have received a copy of the GNU General Public License
51 | along with this program. If not, see .
52 |
53 | ## To Do
54 | ### Tidy up documentation
55 | ### Memory efficiency
56 | - Only load piece data in to memory when it is needed.
57 |
58 | ### Magnet URL Scheme
59 | - https://en.wikipedia.org/wiki/Magnet_URI_scheme
60 |
61 | ### DHT
62 | Options?
63 | - https://github.com/drxzcl/lightdht/
64 | - I like this one best
65 | - Seems to lock out when finding peers
66 | - https://github.com/gsko/mdht
67 |
68 | ### Encryption? PHE
69 | - https://wiki.vuze.com/w/Message_Stream_Encryption
70 |
71 | ### UPnP
72 | - https://code.google.com/archive/p/miranda-upnp/
73 | - Entirely Python code
74 | - http://www.gniibe.org/memo/system/dynamic-ip/upnp.html
75 | - Has dependency on GNUPnP
76 | - https://github.com/miniupnp/miniupnp
77 |
78 |
79 | ** **Always download legal torrents** **
80 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | PYTHorrent
2 | ==========
3 |
4 | This is a BitTorrent client written entirely in Python so that it can be
5 | easily used for experiments. It is a fully working BitTorrent client so
6 | you can use it below as an example. There is no intelligence in this
7 | such as getting rarest peice first. Everything is random.
8 |
9 | It doesn't use ``thread`` or ``multiprocessing`` as it's designed to be
10 | used for experiments, and I don't know how someone may want to use it,
11 | while also making it impractical for general use, but I'd like to
12 | eventually support the most common schemes such as DHT, Magnet URLs, PHE
13 | tDP, and UPnP so it is possible to accept incoming connections.
14 |
15 | Installation
16 | ------------
17 |
18 | PIP
19 | ~~~
20 |
21 | ::
22 |
23 | pip install pythorrent
24 |
25 | From Source
26 | ~~~~~~~~~~~
27 |
28 | ::
29 |
30 | pip install -r requirements.txt
31 | python setup.py install
32 |
33 | Usage
34 | -----
35 |
36 | Depending on how you installed PYTHorrent you may need to go to the root
37 | of the source of the PYTHorrent directory.
38 |
39 | ::
40 |
41 | cd python-pythorrent
42 |
43 | Getting commands
44 | ~~~~~~~~~~~~~~~~
45 |
46 | ::
47 |
48 | python -m pythorrent -h
49 |
50 | Downloading a Torrent using a torrent file
51 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
52 |
53 | ::
54 |
55 | python -m pythorrent --file ubuntu-16.04-desktop-amd64.iso.torrent --path . --log=info
56 |
57 | Overview
58 | --------
59 |
60 | Documentation for the BitTorrent protocol is poor but these sources have
61 | been immensely helpful: -
62 | http://jonas.nitro.dk/bittorrent/bittorrent-rfc.html -
63 | https://wiki.theory.org/BitTorrentSpecification -
64 | http://www.kristenwidman.com/blog/33/how-to-write-a-bittorrent-client-part-1/
65 | -
66 | http://www.kristenwidman.com/blog/71/how-to-write-a-bittorrent-client-part-2/
67 |
68 | License
69 | -------
70 |
71 | AGPLv3
72 | ~~~~~~
73 |
74 | ::
75 |
76 | This program is free software: you can redistribute it and/or modify
77 | it under the terms of the GNU General Public License as published by
78 | the Free Software Foundation, either version 3 of the License, or
79 | (at your option) any later version.
80 |
81 | This program is distributed in the hope that it will be useful,
82 | but WITHOUT ANY WARRANTY; without even the implied warranty of
83 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
84 | GNU General Public License for more details.
85 |
86 | You should have received a copy of the GNU General Public License
87 | along with this program. If not, see .
88 |
89 | To Do
90 | -----
91 |
92 | Tidy up documentation
93 | ~~~~~~~~~~~~~~~~~~~~~
94 |
95 | Memory efficiency
96 | ~~~~~~~~~~~~~~~~~
97 |
98 | - Only load piece data in to memory when it is needed.
99 |
100 | Magnet URL Scheme
101 | ~~~~~~~~~~~~~~~~~
102 |
103 | - https://en.wikipedia.org/wiki/Magnet\_URI\_scheme
104 |
105 | DHT
106 | ~~~
107 |
108 | Options? - https://github.com/drxzcl/lightdht/ - I like this one best -
109 | Seems to lock out when finding peers - https://github.com/gsko/mdht
110 |
111 | Encryption? PHE
112 | ~~~~~~~~~~~~~~~
113 |
114 | - https://wiki.vuze.com/w/Message\_Stream\_Encryption
115 |
116 | UPnP
117 | ~~~~
118 |
119 | - https://code.google.com/archive/p/miranda-upnp/
120 | - Entirely Python code
121 | - http://www.gniibe.org/memo/system/dynamic-ip/upnp.html
122 | - Has dependency on GNUPnP
123 | - https://github.com/miniupnp/miniupnp
124 |
125 | \*\* **Always download legal torrents** \*\*
126 |
--------------------------------------------------------------------------------
/pythorrent/pieces.py:
--------------------------------------------------------------------------------
1 | # This file is part of PYThorrent.
2 | #
3 | # PYThorrent is free software: you can redistribute it and/or modify
4 | # it under the terms of the GNU General Public License as published by
5 | # the Free Software Foundation, either version 3 of the License, or
6 | # (at your option) any later version.
7 | #
8 | # PYThorrent is distributed in the hope that it will be useful,
9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | # GNU General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with PYThorrent. If not, see .
15 |
16 | from hashlib import sha1
17 | from os import path
18 |
19 | import logging
20 |
21 | class Piece(object):
22 | FILE_NAME_TEMPLATE = "{hex}"
23 | @classmethod
24 | def from_path(cls, sha, path):
25 | """
26 | Used to open a piece if it exists on disk.
27 | :param sha: hashlib hash object representing the real sha1 of
28 | the piece.
29 | :param path: path as string to the file as it exists on disk.
30 | """
31 | return cls.from_file(sha,open(path))
32 |
33 | @classmethod
34 | def from_file(cls, sha, f):
35 | """
36 | Used to open a piece if it exists as a file object.
37 | :param sha: hashlib hash object representing the real sha1 of
38 | the piece.
39 | :param f: file object representing the piece.
40 | """
41 | return cls(sha, f.read())
42 |
43 | def __init__(self, sha, data=""):
44 | """
45 | This basic Piece object represents a Piece from a torrent, its
46 | actual hash, and the data associated with it. Data may not
47 | necesserily valid data, could be incomplete, or corrupt.
48 | :param sha: hashlib hash object representing the real sha1 of
49 | the piece.
50 | :param data: string of bytes of the data in the piece.
51 | """
52 | self.sha = sha
53 | self.data = data
54 |
55 | @property
56 | def hex(self):
57 | """
58 | sha1 of the data in the piece as a hex string.
59 | """
60 | return sha1(self.data).hexdigest()
61 |
62 | @property
63 | def digest(self):
64 | """
65 | sha1 of the data in the piece as a binary string.
66 | """
67 | return sha1(self.data).digest()
68 |
69 | @property
70 | def size(self):
71 | """
72 | A shortcut to find what is the next block in the piece that
73 | should be downloaded.
74 | Returns a number representing the size of the piece so far.
75 | """
76 | return len(self.data)
77 |
78 | @property
79 | def valid(self):
80 | """
81 | Returns whether the data in the piece is valid against the sha.
82 | If it is invalid you have several options, perhaps the piece is
83 | incomplete, or the whole thing has been downloaded but it's too
84 | big. Up to the client to make that call.
85 | """
86 | return self.sha == self.digest
87 |
88 | @property
89 | def file_name(self):
90 | return self.FILE_NAME_TEMPLATE.format(hex=self.hex)
91 |
92 | def piece_path(self, save_dir):
93 | """
94 | Generate a path for this piece to be saved to.
95 | :param save_dir: The base path for this file to be saved in to.
96 | """
97 | return path.join(save_dir, self.file_name)
98 |
99 | def save(self, f):
100 | """
101 | Store the data in this piece to the file object.
102 | :param f: File object to save in to.
103 | """
104 | f.write(self.data)
105 |
106 | def clear(self):
107 | """
108 | Empty out the data in this piece.
109 | """
110 | self.data = ""
111 |
112 | def __eq__(self, o):
113 | """
114 | Compare this piece to another piece to see if they're the same.
115 | :param o: The other piece to compare to.
116 | """
117 | return self.sha == o.sha
118 |
119 | class PieceRemote(Piece):
120 | def __init__(self, sha, peer, have=False, *args, **kwargs):
121 | """
122 | Represents a piece at a peer. Data can be empty before it is
123 | downloaded.
124 | :param sha: hashlib hash object representing the real sha1 of
125 | the piece.
126 | :param peer: Peer object used to link back to the torrent if
127 | necessary.
128 | :param have:Whether the Peer has the this piece. True for has,
129 | False for does not have.
130 | """
131 | super(PieceRemote, self).__init__(sha, *args, **kwargs)
132 | self.peer = peer
133 | self.have = have
134 |
135 | def insert_block(self, index, data):
136 | """
137 | Insert a new block of data in to this piece at a specific
138 | location in the data string.
139 | :param index: The start byte to enter the data in to.
140 | """
141 | right_index = index+len(data) # Not sure this is right
142 | self.data = self.data[:index] + data + self.data[right_index:]
143 |
144 | class PieceLocal(Piece):
145 | def __init__(self, sha, data=""):
146 | """
147 | Represents a piece known to this client.
148 | Availability can be used to count how many of this piece exist
149 | among the peers.
150 | :param sha: hashlib hash object representing the real sha1 of
151 | the piece.
152 | :param path: path as string to the file as it exists on disk.
153 | """
154 | super(PieceLocal, self).__init__(sha, "")
155 | self.availability = 0
156 |
157 | def load(self, piece_dir):
158 | """
159 | Load data for piece from disk if path to where pieces are stored
160 | is known.
161 | :param piece_dir: Path as string to where pieces are stored.
162 | """
163 | with open(self.piece_path(piece_dir), "rb") as f:
164 | self.data = f.read()
165 |
166 | def complete(self, piece):
167 | """
168 | Used to merge a PieceRemote back in to a local piece. Once a
169 | piece has been downloaded use this function to copy that data in
170 | to this object.
171 | :param piece: RemotePiece object with the data to copy.
172 | """
173 | self.data = str(piece.data)
174 |
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | PAPER =
8 | BUILDDIR = _build
9 |
10 | # Internal variables.
11 | PAPEROPT_a4 = -D latex_paper_size=a4
12 | PAPEROPT_letter = -D latex_paper_size=letter
13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
14 | # the i18n builder cannot share the environment and doctrees with the others
15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
16 |
17 | .PHONY: help
18 | help:
19 | @echo "Please use \`make ' where is one of"
20 | @echo " html to make standalone HTML files"
21 | @echo " dirhtml to make HTML files named index.html in directories"
22 | @echo " singlehtml to make a single large HTML file"
23 | @echo " pickle to make pickle files"
24 | @echo " json to make JSON files"
25 | @echo " htmlhelp to make HTML files and a HTML help project"
26 | @echo " qthelp to make HTML files and a qthelp project"
27 | @echo " applehelp to make an Apple Help Book"
28 | @echo " devhelp to make HTML files and a Devhelp project"
29 | @echo " epub to make an epub"
30 | @echo " epub3 to make an epub3"
31 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
32 | @echo " latexpdf to make LaTeX files and run them through pdflatex"
33 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
34 | @echo " text to make text files"
35 | @echo " man to make manual pages"
36 | @echo " texinfo to make Texinfo files"
37 | @echo " info to make Texinfo files and run them through makeinfo"
38 | @echo " gettext to make PO message catalogs"
39 | @echo " changes to make an overview of all changed/added/deprecated items"
40 | @echo " xml to make Docutils-native XML files"
41 | @echo " pseudoxml to make pseudoxml-XML files for display purposes"
42 | @echo " linkcheck to check all external links for integrity"
43 | @echo " doctest to run all doctests embedded in the documentation (if enabled)"
44 | @echo " coverage to run coverage check of the documentation (if enabled)"
45 | @echo " dummy to check syntax errors of document sources"
46 |
47 | .PHONY: clean
48 | clean:
49 | rm -rf $(BUILDDIR)/*
50 |
51 | .PHONY: html
52 | html:
53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
54 | @echo
55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
56 |
57 | .PHONY: dirhtml
58 | dirhtml:
59 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
60 | @echo
61 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
62 |
63 | .PHONY: singlehtml
64 | singlehtml:
65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
66 | @echo
67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
68 |
69 | .PHONY: pickle
70 | pickle:
71 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
72 | @echo
73 | @echo "Build finished; now you can process the pickle files."
74 |
75 | .PHONY: json
76 | json:
77 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
78 | @echo
79 | @echo "Build finished; now you can process the JSON files."
80 |
81 | .PHONY: htmlhelp
82 | htmlhelp:
83 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
84 | @echo
85 | @echo "Build finished; now you can run HTML Help Workshop with the" \
86 | ".hhp project file in $(BUILDDIR)/htmlhelp."
87 |
88 | .PHONY: qthelp
89 | qthelp:
90 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
91 | @echo
92 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \
93 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
94 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PYThorrent.qhcp"
95 | @echo "To view the help file:"
96 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PYThorrent.qhc"
97 |
98 | .PHONY: applehelp
99 | applehelp:
100 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
101 | @echo
102 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
103 | @echo "N.B. You won't be able to view it unless you put it in" \
104 | "~/Library/Documentation/Help or install it in your application" \
105 | "bundle."
106 |
107 | .PHONY: devhelp
108 | devhelp:
109 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
110 | @echo
111 | @echo "Build finished."
112 | @echo "To view the help file:"
113 | @echo "# mkdir -p $$HOME/.local/share/devhelp/PYThorrent"
114 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PYThorrent"
115 | @echo "# devhelp"
116 |
117 | .PHONY: epub
118 | epub:
119 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
120 | @echo
121 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
122 |
123 | .PHONY: epub3
124 | epub3:
125 | $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3
126 | @echo
127 | @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3."
128 |
129 | .PHONY: latex
130 | latex:
131 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
132 | @echo
133 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
134 | @echo "Run \`make' in that directory to run these through (pdf)latex" \
135 | "(use \`make latexpdf' here to do that automatically)."
136 |
137 | .PHONY: latexpdf
138 | latexpdf:
139 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
140 | @echo "Running LaTeX files through pdflatex..."
141 | $(MAKE) -C $(BUILDDIR)/latex all-pdf
142 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
143 |
144 | .PHONY: latexpdfja
145 | latexpdfja:
146 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
147 | @echo "Running LaTeX files through platex and dvipdfmx..."
148 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
149 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
150 |
151 | .PHONY: text
152 | text:
153 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
154 | @echo
155 | @echo "Build finished. The text files are in $(BUILDDIR)/text."
156 |
157 | .PHONY: man
158 | man:
159 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
160 | @echo
161 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
162 |
163 | .PHONY: texinfo
164 | texinfo:
165 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
166 | @echo
167 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
168 | @echo "Run \`make' in that directory to run these through makeinfo" \
169 | "(use \`make info' here to do that automatically)."
170 |
171 | .PHONY: info
172 | info:
173 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
174 | @echo "Running Texinfo files through makeinfo..."
175 | make -C $(BUILDDIR)/texinfo info
176 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
177 |
178 | .PHONY: gettext
179 | gettext:
180 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
181 | @echo
182 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
183 |
184 | .PHONY: changes
185 | changes:
186 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
187 | @echo
188 | @echo "The overview file is in $(BUILDDIR)/changes."
189 |
190 | .PHONY: linkcheck
191 | linkcheck:
192 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
193 | @echo
194 | @echo "Link check complete; look for any errors in the above output " \
195 | "or in $(BUILDDIR)/linkcheck/output.txt."
196 |
197 | .PHONY: doctest
198 | doctest:
199 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
200 | @echo "Testing of doctests in the sources finished, look at the " \
201 | "results in $(BUILDDIR)/doctest/output.txt."
202 |
203 | .PHONY: coverage
204 | coverage:
205 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
206 | @echo "Testing of coverage in the sources finished, look at the " \
207 | "results in $(BUILDDIR)/coverage/python.txt."
208 |
209 | .PHONY: xml
210 | xml:
211 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
212 | @echo
213 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml."
214 |
215 | .PHONY: pseudoxml
216 | pseudoxml:
217 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
218 | @echo
219 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
220 |
221 | .PHONY: dummy
222 | dummy:
223 | $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy
224 | @echo
225 | @echo "Build finished. Dummy builder generates no files."
226 |
--------------------------------------------------------------------------------
/pythorrent/peer_stores.py:
--------------------------------------------------------------------------------
1 | # This file is part of PYTHorrent.
2 | #
3 | # PYTHorrent is free software: you can redistribute it and/or modify
4 | # it under the terms of the GNU General Public License as published by
5 | # the Free Software Foundation, either version 3 of the License, or
6 | # (at your option) any later version.
7 | #
8 | # PYTHorrent is distributed in the hope that it will be useful,
9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | # GNU General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with PYTHorrent. If not, see .
15 |
16 | import socket
17 | import random
18 | from urlparse import urlparse
19 | from struct import unpack
20 | from datetime import datetime, timedelta
21 |
22 | from . import splice, BitTorrentException
23 | from .peer import Peer
24 |
25 | import requests
26 | from torrentool.bencode import Bencode
27 |
28 | import logging
29 |
30 | def decode_binary_peers(peers):
31 | """ Return a list of IPs and ports, given a binary list of peers,
32 | from a tracker response. """
33 |
34 | peers = splice(peers, 6) # Cut the response at the end of every peer
35 | return [(socket.inet_ntoa(p[:4]), decode_port(p[4:])) for p in peers]
36 |
37 | def decode_port(port):
38 | """ Given a big-endian encoded port, returns the numerical port. """
39 | return unpack(">H", port)[0]
40 |
41 | def store_from_url(url):
42 | """
43 | Get a store object based upon the URL used to access that peer
44 | store.
45 | :param url: URL used to access the peer store as string.
46 | """
47 | parsed_url = urlparse(url)
48 | if parsed_url.scheme.startswith("http"):
49 | return HTTPTracker
50 | if parsed_url.scheme.startswith("udp"):
51 | return UDPTracker
52 | # DHT would go here
53 |
54 | class TrackerException(Exception):
55 | pass
56 |
57 | class Tracker(object)
58 | PEER = Peer
59 | TRACKER_INTERVAL = 1800 # seconds
60 |
61 | def __init__(self, tracker_url, torrent):
62 | """
63 | Represents a tracker to get a list of peers from.
64 | :param tracker_url: URL to access the tracker at.
65 | :param torrent: Torrent object to hook back in to details needed
66 | to access the tracker.
67 | """
68 | self.tracker_url = tracker_url
69 | self.torrent = torrent
70 | self._peers = {}
71 | self.tracker_interval = self.TRACKER_INTERVAL
72 | self.last_run = None
73 |
74 | @property
75 | def now(self):
76 | """
77 | Use a consistent datetime now value.
78 | Returns DateTime object with value of now.
79 | """
80 | return datetime.utcnow()
81 |
82 | @property
83 | def delta(self):
84 | """
85 | Shortcut to get TimeDelta for delay between tracker requests.
86 | Returns TimeDelta object representing delay between tracker
87 | requests.
88 | """
89 | return timedelta(seconds=self.tracker_interval)
90 |
91 | @property
92 | def next_run(self):
93 | """
94 | Shortcut to find out when the tracker request should be next
95 | run.
96 | Returns DateTime object representing the next time the tracker
97 | wants an announce from the client as a minimum.
98 | """
99 | return self.last_run + self.delta
100 |
101 | @property
102 | def ok_to_announce(self):
103 | """
104 | Returns True when enough time has elapsed since last_run to
105 | announce again, and False if it has not, or has not been set,
106 | but also handles if has never been run.
107 | """
108 | if self.last_run is None:
109 | return True
110 | return self.now > self.next_run
111 |
112 | @property
113 | def peers(self):
114 | """
115 | If it is ok to get new peers will update the list of peers, then
116 | will return the list of peers.
117 | Returns list of Peer objects.
118 | """
119 | if self.ok_to_announce:
120 | logging.debug("Announcing to {url}".format(
121 | url=self.tracker_url
122 | ))
123 | self._peers.update(self.announce())
124 | return self._peers
125 |
126 | def announce(self):
127 | raise NotImplemented("Use this method to announce to tracker")
128 |
129 | class HTTPTracker(Tracker):
130 | @property
131 | def announce_payload(self):
132 | """
133 | Returns the query params used to announce client to tracker.
134 | Returns dictionary of query params.
135 | """
136 | return {
137 | "info_hash" : self.torrent.info_hash,
138 | "peer_id" : self.torrent.peer_id,
139 | "port" : self.torrent.port,
140 | "uploaded" : self.torrent.uploaded,
141 | "downloaded" : self.torrent.downloaded,
142 | "left" : self.torrent.remaining,
143 | "compact" : 1
144 | }
145 |
146 | def announce(self):
147 | """
148 | Announces client to tracker and handles response.
149 | Returns dictionary of peers.
150 | """
151 |
152 | # Send the request
153 | try:
154 | response = requests.get(
155 | self.tracker_url,
156 | params=self.announce_payload,
157 | allow_redirects=False
158 | )
159 | logging.debug("Tracker URL: {0}".format(response.url))
160 | except requests.ConnectionError as e:
161 | logging.warn(
162 | "Tracker not found: {0}".format(
163 | self.tracker_url
164 | )
165 | )
166 | return {}
167 |
168 | if response.status_code < 200 or response.status_code >= 300:
169 | raise BitTorrentException(
170 | "Tracker response error '{0}' for URL: {1}".format(
171 | response.content,
172 | response.url
173 | )
174 | )
175 |
176 | self.last_run = self.now
177 |
178 | decoded_response = Bencode.decode(response.content)
179 |
180 | self.tracker_interval = decoded_response.get(
181 | 'interval',
182 | self.TRACKER_INTERVAL
183 | )
184 | logging.debug("Tracking interval set to: {interval}".format(
185 | interval=self.tracker_interval
186 | ))
187 |
188 | if "failure reason" in decoded_response:
189 | raise BitTorrentException(decoded_response["failure reason"])
190 |
191 | if "peers" in decoded_response: # ignoring `peer6` (ipv6) for now
192 | peers = decode_binary_peers(decoded_response['peers'])
193 | else:
194 | peers = []
195 |
196 | return dict(map(
197 | lambda hostport: (
198 | hostport, self.PEER(hostport, self.torrent)
199 | ),
200 | peers
201 | ))
202 |
203 | class UDPTracker(Tracker):
204 | DEFAULT_CONNECTION_ID = 0x41727101980
205 |
206 | class EACTION:
207 | NEW_CONNECTION = 0x0
208 | SCRAPE = 0x2
209 | ERROR = 0x3
210 |
211 | @staticmethod
212 | def generate_transaction_id():
213 | return int(random.randrange(0, 255))
214 |
215 | def __init__(self, *args, **kwargs):
216 | self.tracker_url_parts = urlparse(self.tracker_url)
217 | self._socket = None
218 | self._connection = None
219 |
220 | @property
221 | def socket(self):
222 | if self._socket is None:
223 | self._socket = socket.socket(
224 | socket.AF_INET,
225 | socket.SOCK_DGRAM
226 | )
227 | return self._socket
228 |
229 | @property
230 | def connection(self):
231 | if self._connection is None:
232 | ip = socket.gethostbyname(self.tracker_url_parts.hostname)
233 | self._connection = (ip, self.tracker_url_parts.port)
234 | return self._connection
235 |
236 | def announce(self):
237 | connection_id = self.connection_request()
238 | peers, leechers, complete = self.scrape_request(connection_id)
239 |
240 | def generate_message(self,
241 | connection_id,
242 | action,
243 | transaction_id,
244 | payload=""
245 | ):
246 | buf = struct.pack("!q", connection_id)
247 | buf += struct.pack("!i", action)
248 | buf += struct.pack("!i", transaction_id)
249 | buf += payload
250 | return buf
251 |
252 | def send(self, msg):
253 | self.socket.sendto(msg, self.connection);
254 |
255 | def connection_request(self):
256 | transaction_id = self.generate_transaction_id()
257 | connection_request = self.generate_message(
258 | self.DEFAULT_CONNECTION_ID,
259 | self.EACTION.NEW_CONNECTION,
260 | transaction_id
261 | )
262 |
263 | self.send(connection_request)
264 |
265 | return parse_connection_response(transaction_id)
266 |
267 |
268 | def parse_connection_response(self, transaction_id):
269 | buf = self.socket.recvfrom(2048)[0]
270 |
271 | if len(buf) < 16:
272 | raise TrackerException(
273 | "Wrong response length getting connection id: " \
274 | "{0}".format(len(buf))
275 | )
276 | action = struct.unpack_from("!i", buf)[0]
277 |
278 | res_transaction_id = struct.unpack_from("!i", buf, 4)[0]
279 | if res_transaction_id != transaction_id:
280 | raise TrackerException("Transaction ID doesnt match in " \
281 | "connection response during connection request. " \
282 | "Expected {local}, got {response}".format(
283 | local = transaction_id,
284 | response = res_transaction_id
285 | )
286 | )
287 |
288 | if action == self.EACTION.NEW_CONNECTION:
289 | connection_id = struct.unpack_from("!q", buf, 8)[0]
290 | return connection_id
291 | elif action == self.EACTION.ERROR:
292 | error = struct.unpack_from("!s", buf, 8)
293 | raise TrackerException("Error while trying to get a " \
294 | "connection response: {0}".format(error))
295 |
296 | def scrape_request(self, connection_id):
297 | transaction_id = self.generate_transaction_id()
298 | request = self.generate_message(
299 | connection_id,
300 | self.EACTION.SCRAPE,
301 | transaction_id,
302 | struct.pack("!20s", self.torrent.info_hash)
303 | )
304 | self.send(request)
305 |
306 | return parse_scrape_response(transaction_id, info_hash)
307 |
308 | def parse_scrape_response(self, sent_transaction_id, info_hash):
309 | buf = self.socket.recvfrom(2048)[0]
310 | if len(buf) < 16:
311 | raise TrackerException(
312 | "Wrong response length while scraping: {0}".format(
313 | len(buf)
314 | )
315 | )
316 |
317 | action = struct.unpack_from("!i", buf)[0]
318 | res_transaction_id = struct.unpack_from("!i", buf, 4)[0]
319 | if res_transaction_id != sent_transaction_id:
320 | raise TrackerException("Transaction ID doesnt match in " \
321 | "connection response during scrape. Expected " \
322 | "{local}, got {response}".format(
323 | local = transaction_id,
324 | response = res_transaction_id
325 | )
326 | )
327 |
328 | if action == self.EACTION.SCRAPE:
329 | offset = 8;
330 | seeds = struct.unpack_from("!i", buf, offset)[0]
331 | offset += 4
332 | complete = struct.unpack_from("!i", buf, offset)[0]
333 | offset += 4
334 | leeches = struct.unpack_from("!i", buf, offset)[0]
335 | offset += 4
336 | return seeds, leeches, complete
337 |
338 | elif action == self.EACTION.ERROR:
339 | #an error occured, try and extract the error string
340 | error = struct.unpack_from("!s", buf, 8)
341 | raise TrackerException("Error while scraping: %s" % error)
342 |
343 |
344 |
--------------------------------------------------------------------------------
/docs/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import sys
4 |
5 | sys.path.insert(0, "pythorrent")
6 |
7 | #
8 | # PYThorrent documentation build configuration file, created by
9 | # sphinx-quickstart on Mon Jul 25 17:55:13 2016.
10 | #
11 | # This file is execfile()d with the current directory set to its
12 | # containing dir.
13 | #
14 | # Note that not all possible configuration values are present in this
15 | # autogenerated file.
16 | #
17 | # All configuration values have a default; values that are commented out
18 | # serve to show the default.
19 |
20 | # If extensions (or modules to document with autodoc) are in another directory,
21 | # add these directories to sys.path here. If the directory is relative to the
22 | # documentation root, use os.path.abspath to make it absolute, like shown here.
23 | #
24 | # import os
25 | # import sys
26 | # sys.path.insert(0, os.path.abspath('.'))
27 |
28 | # -- General configuration ------------------------------------------------
29 |
30 | # If your documentation needs a minimal Sphinx version, state it here.
31 | #
32 | # needs_sphinx = '1.0'
33 |
34 | # Add any Sphinx extension module names here, as strings. They can be
35 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
36 | # ones.
37 | extensions = [
38 | 'sphinx.ext.autodoc',
39 | 'sphinx.ext.todo',
40 | 'sphinx.ext.viewcode',
41 | 'sphinx.ext.githubpages',
42 | ]
43 |
44 | # Add any paths that contain templates here, relative to this directory.
45 | templates_path = ['_templates']
46 |
47 | # The suffix(es) of source filenames.
48 | # You can specify multiple suffix as a list of string:
49 | #
50 | # source_suffix = ['.rst', '.md']
51 | source_suffix = '.rst'
52 |
53 | # The encoding of source files.
54 | #
55 | # source_encoding = 'utf-8-sig'
56 |
57 | # The master toctree document.
58 | master_doc = 'index'
59 |
60 | # General information about the project.
61 | project = u'PYThorrent'
62 | copyright = u'2016, Matt Copperwaite'
63 | author = u'Matt Copperwaite'
64 |
65 | # The version info for the project you're documenting, acts as replacement for
66 | # |version| and |release|, also used in various other places throughout the
67 | # built documents.
68 | #
69 | # The short X.Y version.
70 | version = u'0.1a'
71 | # The full version, including alpha/beta/rc tags.
72 | release = u'0.1a'
73 |
74 | # The language for content autogenerated by Sphinx. Refer to documentation
75 | # for a list of supported languages.
76 | #
77 | # This is also used if you do content translation via gettext catalogs.
78 | # Usually you set "language" from the command line for these cases.
79 | language = None
80 |
81 | # There are two options for replacing |today|: either, you set today to some
82 | # non-false value, then it is used:
83 | #
84 | # today = ''
85 | #
86 | # Else, today_fmt is used as the format for a strftime call.
87 | #
88 | # today_fmt = '%B %d, %Y'
89 |
90 | # List of patterns, relative to source directory, that match files and
91 | # directories to ignore when looking for source files.
92 | # This patterns also effect to html_static_path and html_extra_path
93 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
94 |
95 | # The reST default role (used for this markup: `text`) to use for all
96 | # documents.
97 | #
98 | # default_role = None
99 |
100 | # If true, '()' will be appended to :func: etc. cross-reference text.
101 | #
102 | # add_function_parentheses = True
103 |
104 | # If true, the current module name will be prepended to all description
105 | # unit titles (such as .. function::).
106 | #
107 | # add_module_names = True
108 |
109 | # If true, sectionauthor and moduleauthor directives will be shown in the
110 | # output. They are ignored by default.
111 | #
112 | # show_authors = False
113 |
114 | # The name of the Pygments (syntax highlighting) style to use.
115 | pygments_style = 'sphinx'
116 |
117 | # A list of ignored prefixes for module index sorting.
118 | # modindex_common_prefix = []
119 |
120 | # If true, keep warnings as "system message" paragraphs in the built documents.
121 | # keep_warnings = False
122 |
123 | # If true, `todo` and `todoList` produce output, else they produce nothing.
124 | todo_include_todos = True
125 |
126 |
127 | # -- Options for HTML output ----------------------------------------------
128 |
129 | # The theme to use for HTML and HTML Help pages. See the documentation for
130 | # a list of builtin themes.
131 | #
132 | html_theme = 'alabaster'
133 |
134 | # Theme options are theme-specific and customize the look and feel of a theme
135 | # further. For a list of options available for each theme, see the
136 | # documentation.
137 | #
138 | # html_theme_options = {}
139 |
140 | # Add any paths that contain custom themes here, relative to this directory.
141 | # html_theme_path = []
142 |
143 | # The name for this set of Sphinx documents.
144 | # " v documentation" by default.
145 | #
146 | # html_title = u'PYThorrent v0.1a'
147 |
148 | # A shorter title for the navigation bar. Default is the same as html_title.
149 | #
150 | # html_short_title = None
151 |
152 | # The name of an image file (relative to this directory) to place at the top
153 | # of the sidebar.
154 | #
155 | # html_logo = None
156 |
157 | # The name of an image file (relative to this directory) to use as a favicon of
158 | # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
159 | # pixels large.
160 | #
161 | # html_favicon = None
162 |
163 | # Add any paths that contain custom static files (such as style sheets) here,
164 | # relative to this directory. They are copied after the builtin static files,
165 | # so a file named "default.css" will overwrite the builtin "default.css".
166 | html_static_path = ['_static']
167 |
168 | # Add any extra paths that contain custom files (such as robots.txt or
169 | # .htaccess) here, relative to this directory. These files are copied
170 | # directly to the root of the documentation.
171 | #
172 | # html_extra_path = []
173 |
174 | # If not None, a 'Last updated on:' timestamp is inserted at every page
175 | # bottom, using the given strftime format.
176 | # The empty string is equivalent to '%b %d, %Y'.
177 | #
178 | # html_last_updated_fmt = None
179 |
180 | # If true, SmartyPants will be used to convert quotes and dashes to
181 | # typographically correct entities.
182 | #
183 | # html_use_smartypants = True
184 |
185 | # Custom sidebar templates, maps document names to template names.
186 | #
187 | # html_sidebars = {}
188 |
189 | # Additional templates that should be rendered to pages, maps page names to
190 | # template names.
191 | #
192 | # html_additional_pages = {}
193 |
194 | # If false, no module index is generated.
195 | #
196 | # html_domain_indices = True
197 |
198 | # If false, no index is generated.
199 | #
200 | # html_use_index = True
201 |
202 | # If true, the index is split into individual pages for each letter.
203 | #
204 | # html_split_index = False
205 |
206 | # If true, links to the reST sources are added to the pages.
207 | #
208 | # html_show_sourcelink = True
209 |
210 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
211 | #
212 | # html_show_sphinx = True
213 |
214 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
215 | #
216 | # html_show_copyright = True
217 |
218 | # If true, an OpenSearch description file will be output, and all pages will
219 | # contain a tag referring to it. The value of this option must be the
220 | # base URL from which the finished HTML is served.
221 | #
222 | # html_use_opensearch = ''
223 |
224 | # This is the file name suffix for HTML files (e.g. ".xhtml").
225 | # html_file_suffix = None
226 |
227 | # Language to be used for generating the HTML full-text search index.
228 | # Sphinx supports the following languages:
229 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
230 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
231 | #
232 | # html_search_language = 'en'
233 |
234 | # A dictionary with options for the search language support, empty by default.
235 | # 'ja' uses this config value.
236 | # 'zh' user can custom change `jieba` dictionary path.
237 | #
238 | # html_search_options = {'type': 'default'}
239 |
240 | # The name of a javascript file (relative to the configuration directory) that
241 | # implements a search results scorer. If empty, the default will be used.
242 | #
243 | # html_search_scorer = 'scorer.js'
244 |
245 | # Output file base name for HTML help builder.
246 | htmlhelp_basename = 'PYThorrentdoc'
247 |
248 | # -- Options for LaTeX output ---------------------------------------------
249 |
250 | latex_elements = {
251 | # The paper size ('letterpaper' or 'a4paper').
252 | #
253 | # 'papersize': 'letterpaper',
254 |
255 | # The font size ('10pt', '11pt' or '12pt').
256 | #
257 | # 'pointsize': '10pt',
258 |
259 | # Additional stuff for the LaTeX preamble.
260 | #
261 | # 'preamble': '',
262 |
263 | # Latex figure (float) alignment
264 | #
265 | # 'figure_align': 'htbp',
266 | }
267 |
268 | # Grouping the document tree into LaTeX files. List of tuples
269 | # (source start file, target name, title,
270 | # author, documentclass [howto, manual, or own class]).
271 | latex_documents = [
272 | (master_doc, 'PYThorrent.tex', u'PYThorrent Documentation',
273 | u'Matt Copperwaite', 'manual'),
274 | ]
275 |
276 | # The name of an image file (relative to this directory) to place at the top of
277 | # the title page.
278 | #
279 | # latex_logo = None
280 |
281 | # For "manual" documents, if this is true, then toplevel headings are parts,
282 | # not chapters.
283 | #
284 | # latex_use_parts = False
285 |
286 | # If true, show page references after internal links.
287 | #
288 | # latex_show_pagerefs = False
289 |
290 | # If true, show URL addresses after external links.
291 | #
292 | # latex_show_urls = False
293 |
294 | # Documents to append as an appendix to all manuals.
295 | #
296 | # latex_appendices = []
297 |
298 | # It false, will not define \strong, \code, itleref, \crossref ... but only
299 | # \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added
300 | # packages.
301 | #
302 | # latex_keep_old_macro_names = True
303 |
304 | # If false, no module index is generated.
305 | #
306 | # latex_domain_indices = True
307 |
308 |
309 | # -- Options for manual page output ---------------------------------------
310 |
311 | # One entry per manual page. List of tuples
312 | # (source start file, name, description, authors, manual section).
313 | man_pages = [
314 | (master_doc, 'pythorrent', u'PYThorrent Documentation',
315 | [author], 1)
316 | ]
317 |
318 | # If true, show URL addresses after external links.
319 | #
320 | # man_show_urls = False
321 |
322 |
323 | # -- Options for Texinfo output -------------------------------------------
324 |
325 | # Grouping the document tree into Texinfo files. List of tuples
326 | # (source start file, target name, title, author,
327 | # dir menu entry, description, category)
328 | texinfo_documents = [
329 | (master_doc, 'PYThorrent', u'PYThorrent Documentation',
330 | author, 'PYThorrent', 'One line description of project.',
331 | 'Miscellaneous'),
332 | ]
333 |
334 | # Documents to append as an appendix to all manuals.
335 | #
336 | # texinfo_appendices = []
337 |
338 | # If false, no module index is generated.
339 | #
340 | # texinfo_domain_indices = True
341 |
342 | # How to display URL addresses: 'footnote', 'no', or 'inline'.
343 | #
344 | # texinfo_show_urls = 'footnote'
345 |
346 | # If true, do not generate a @detailmenu in the "Top" node's menu.
347 | #
348 | # texinfo_no_detailmenu = False
349 |
350 |
351 | # -- Options for Epub output ----------------------------------------------
352 |
353 | # Bibliographic Dublin Core info.
354 | epub_title = project
355 | epub_author = author
356 | epub_publisher = author
357 | epub_copyright = copyright
358 |
359 | # The basename for the epub file. It defaults to the project name.
360 | # epub_basename = project
361 |
362 | # The HTML theme for the epub output. Since the default themes are not
363 | # optimized for small screen space, using the same theme for HTML and epub
364 | # output is usually not wise. This defaults to 'epub', a theme designed to save
365 | # visual space.
366 | #
367 | # epub_theme = 'epub'
368 |
369 | # The language of the text. It defaults to the language option
370 | # or 'en' if the language is not set.
371 | #
372 | # epub_language = ''
373 |
374 | # The scheme of the identifier. Typical schemes are ISBN or URL.
375 | # epub_scheme = ''
376 |
377 | # The unique identifier of the text. This can be a ISBN number
378 | # or the project homepage.
379 | #
380 | # epub_identifier = ''
381 |
382 | # A unique identification for the text.
383 | #
384 | # epub_uid = ''
385 |
386 | # A tuple containing the cover image and cover page html template filenames.
387 | #
388 | # epub_cover = ()
389 |
390 | # A sequence of (type, uri, title) tuples for the guide element of content.opf.
391 | #
392 | # epub_guide = ()
393 |
394 | # HTML files that should be inserted before the pages created by sphinx.
395 | # The format is a list of tuples containing the path and title.
396 | #
397 | # epub_pre_files = []
398 |
399 | # HTML files that should be inserted after the pages created by sphinx.
400 | # The format is a list of tuples containing the path and title.
401 | #
402 | # epub_post_files = []
403 |
404 | # A list of files that should not be packed into the epub file.
405 | epub_exclude_files = ['search.html']
406 |
407 | # The depth of the table of contents in toc.ncx.
408 | #
409 | # epub_tocdepth = 3
410 |
411 | # Allow duplicate toc entries.
412 | #
413 | # epub_tocdup = True
414 |
415 | # Choose between 'default' and 'includehidden'.
416 | #
417 | # epub_tocscope = 'default'
418 |
419 | # Fix unsupported image types using the Pillow.
420 | #
421 | # epub_fix_images = False
422 |
423 | # Scale large images.
424 | #
425 | # epub_max_image_width = 0
426 |
427 | # How to display URL addresses: 'footnote', 'no', or 'inline'.
428 | #
429 | # epub_show_urls = 'inline'
430 |
431 | # If false, no index is generated.
432 | #
433 | # epub_use_index = True
434 |
--------------------------------------------------------------------------------
/pythorrent/torrent.py:
--------------------------------------------------------------------------------
1 | # This file is part of PYThorrent.
2 | #
3 | # PYThorrent is free software: you can redistribute it and/or modify
4 | # it under the terms of the GNU General Public License as published by
5 | # the Free Software Foundation, either version 3 of the License, or
6 | # (at your option) any later version.
7 | #
8 | # PYThorrent is distributed in the hope that it will be useful,
9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | # GNU General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with PYThorrent. If not, see .
15 |
16 | from hashlib import sha1
17 | from random import choice, randint
18 | import string
19 | import socket
20 | from struct import pack, unpack
21 | from collections import OrderedDict
22 | import os
23 | from random import choice
24 |
25 | from . import splice
26 | from .peer_stores import store_from_url
27 | from .peer import Peer, BitTorrentPeerException
28 | from .pieces import PieceLocal
29 | from . import BitTorrentException
30 |
31 | import requests
32 | from torrentool.bencode import Bencode
33 | from bitstring import BitArray
34 |
35 | import logging
36 |
37 | class Torrent(object):
38 | PIECE = PieceLocal
39 | CLIENT_NAME = "pythorrent"
40 | CLIENT_ID = "PY"
41 | CLIENT_VERSION = "0001"
42 | CLIENT_ID_LENGTH = 20
43 | CHAR_LIST = string.ascii_letters + string.digits
44 | PIECE_DIR = "_pieces"
45 | PROTOCOL_ID = "BitTorrent protocol"
46 | RESERVED_AREA = "\x00"*8
47 | DEFAULT_PORT = 6881
48 | MAX_PEERS = 20
49 | TORRENT_CACHE_URL="https://torcache.net/torrent/" \
50 | "{info_hash_hex}.torrent"
51 |
52 | @classmethod
53 | def from_info_hash(cls, info_hash, save_path):
54 | """
55 | Takes an info hash of a torrent as a binary string and builds a
56 | torrent from it.
57 | :param info_hash: A hashlib hash object.
58 | :param save_path: A string path to where the torrent should be
59 | saved.
60 | """
61 | return cls.from_info_hash_hex(
62 | info_hash.encode("hex")
63 | )
64 |
65 | @classmethod
66 | def from_info_hash_sha(cls, info_hash_sha, save_path):
67 | """
68 | Takes an info hash of a torrent as a hashlib sha object and
69 | builds a torrent from it.
70 | :param info_hash_sha:A hashlib hashed object.
71 | :param save_path: A string path to where the torrent should be
72 | saved.
73 | """
74 | return cls.from_info_hash_hex(
75 | info_hash_sha.hexdigest()
76 | )
77 |
78 | @classmethod
79 | def from_info_hash_hex(cls, info_hash_hex, save_path):
80 | """
81 | Takes an info hash of a torrent as a string and builds a URL for
82 | it so it can be looked up.
83 | :param info_hash_hex: A hex encoded string of the torrent's info
84 | hash.
85 | :param save_path: A string path to where the torrent should be
86 | saved.
87 | """
88 | url = self.TORRENT_CACHE_URL.format(
89 | info_hash_sha.hexdigest()
90 | )
91 | return cls.from_url(url)
92 |
93 | @classmethod
94 | def from_url(cls, url, save_path):
95 | """
96 | Takes a torrent from a URL, downloads it and loads it.
97 | :param url: The URL to the torrent file
98 | :param save_path: A string path to where the torrent should be
99 | saved.
100 | """
101 | response = requests.get(url)
102 | if response.status_code < 200 or response.status_code >= 300:
103 | raise BitTorrentException("Torrent file not found at:" \
104 | "{url}".format(url=url)
105 | )
106 | return cls.from_string(response.content, save_path)
107 |
108 | @classmethod
109 | def from_path(cls, path, save_path):
110 | """
111 | Takes a torrent from a path and loads it.
112 | :param path: A path as string to the path torrent file.
113 | :param save_path: A string path to where the torrent should be
114 | saved.
115 | """
116 | return cls.from_torrent_dict(
117 | Bencode.read_file(path),
118 | save_path
119 | )
120 |
121 | @classmethod
122 | def from_string(cls, s, save_path):
123 | """
124 | Takes a torrent file as a string and loads it.
125 | :param s:
126 | :param save_path: A string path to where the torrent should be
127 | saved.
128 | """
129 | return cls.from_torrent_dict(
130 | Bencode.read_string(s),
131 | save_path
132 | )
133 |
134 | @classmethod
135 | def from_torrent_dict(cls, metainfo, save_path):
136 | """
137 | Takes a torrent metainfo dictionary object and processes it for
138 | use in this object.
139 | :param metainfo:
140 | :param save_path: A string path to where the torrent should be
141 | saved.
142 | """
143 | info = metainfo['info']
144 | files = OrderedDict()
145 | if 'files' in info:
146 | for f in info['files']:
147 | files[os.path.join(*f['path'])] = f['length']
148 | else:
149 | files[info['name']] = info['length']
150 |
151 | return cls(
152 | name=info['name'],
153 | announce_urls=map(
154 | lambda (url,): url, metainfo['announce-list']
155 | ),
156 | # Note that info_hash is generated here because torrentool
157 | # returns the info_hash as hex encoded, which is really not
158 | # useful in most situations
159 | info_hash=sha1(Bencode.encode(info)).digest(),
160 | piece_length=info['piece length'],
161 | files=files,
162 | piece_hashes=splice(info['pieces'], 20),
163 | save_path=save_path
164 | )
165 |
166 | def __init__(
167 | self, name, announce_urls, info_hash, piece_length, files, \
168 | piece_hashes, save_path
169 | ):
170 | """
171 | Represent a Torrent file and handle downloading and saving.
172 | :param name: Name of the torrent
173 | :param announce_urls: a list of URLs to find DHTs or trackers.
174 | The scheme is used to identify what kind of announce it is.
175 | http/https for normal HTTP trackers
176 | :param info_hash:The binary encoded info hash.
177 | :param piece_length: the default length of all (except the last)
178 | piece
179 | :param files: A dictionary of all the files where the key is the
180 | name of the file and the value is the size.
181 | :param piece_hashes: A list of all piece hashes as strings
182 | :param save_path: A string path to where the torrent should be
183 | saved.
184 | """
185 | self.name = name
186 | self.announce_urls = announce_urls
187 | self.info_hash = info_hash
188 | self.piece_length = piece_length
189 | self.files = files
190 | self.piece_hashes = piece_hashes
191 | self.save_path = save_path
192 |
193 | self._peer_stores = None
194 | self._pieces = None
195 | self._peer_id = None
196 |
197 | self._peers = {}
198 |
199 | @property
200 | def handshake_message(self):
201 | """
202 | Generate the string used to declare the protocol when passing
203 | messages during handshake
204 | """
205 | return "".join([
206 | chr(len(self.PROTOCOL_ID)),
207 | self.PROTOCOL_ID,
208 | self.RESERVED_AREA,
209 | self.info_hash,
210 | self.peer_id
211 | ])
212 |
213 | @property
214 | def peer_id(self):
215 | """
216 | Generate the peer id so that it is possible to identify other
217 | clients, and identify if you've connected to your own client
218 | """
219 | if self._peer_id is None:
220 | known_id = "-{id_}{version}-".format(
221 | id_=self.CLIENT_ID,
222 | version=self.CLIENT_VERSION,
223 | )
224 | remaining_length = self.CLIENT_ID_LENGTH - len(known_id)
225 | gubbins = "".join(
226 | [ choice(self.CHAR_LIST) for _ in range(remaining_length) ]
227 | )
228 | self._peer_id = known_id + gubbins
229 | return self._peer_id
230 |
231 | @property
232 | def port(self):
233 | """
234 | External port being used for incoming connections
235 | """
236 | return self.DEFAULT_PORT
237 |
238 | @property
239 | def peer_stores(self):
240 | """
241 | Returns a list of all the peer stores set up
242 | """
243 | if self._peer_stores is None:
244 | self._peer_stores = {}
245 | for url in self.announce_urls:
246 | self._peer_stores[url] = store_from_url(url)(url, self)
247 | return self._peer_stores
248 |
249 | @property
250 | def total_size(self):
251 | """
252 | The size of all the files
253 | """
254 | return sum(self.files.values())
255 |
256 | @property
257 | def downloaded(self):
258 | """
259 | Calculate the size of all the pieces that have been downloaded
260 | so far
261 | """
262 | return sum(map(
263 | lambda piece: self.piece_length if piece.valid else 0,
264 | self.pieces.values()
265 | ))
266 |
267 | @property
268 | def uploaded(self):
269 | # TODO
270 | return 0
271 |
272 | @property
273 | def remaining(self):
274 | """
275 | Calculates how much is left
276 | """
277 | return self.total_size - self.downloaded
278 |
279 | @property
280 | def complete(self):
281 | """
282 | Checks if all pieces have downloaded
283 | """
284 | return not any(map(lambda piece: not piece.valid,
285 | self.pieces.values()
286 | ))
287 |
288 | @property
289 | def peers(self):
290 | """
291 | A list of peers that gets updated when necessary
292 | """
293 | for peer_store in self.peer_stores.values():
294 | self._peers.update(peer_store.peers)
295 | return self._peers
296 |
297 | @property
298 | def pieces(self):
299 | """
300 | Map the pieces from the torrent file to memory.
301 | """
302 | if self._pieces is None:
303 | self._pieces = OrderedDict()
304 | for hash_index in range(len(self.piece_hashes)):
305 | piece_hash = self.piece_hashes[hash_index]
306 | piece = self.PIECE(piece_hash, hash_index)
307 | piece_path = piece.piece_path(self.piece_directory)
308 | if os.path.isfile(piece_path):
309 | logging.info("Piece found on disk: {0}".format(
310 | piece_path
311 | ))
312 | piece.load(piece_path)
313 | if not piece.valid:
314 | raise Exception("Not valid")
315 | logging.warning("Piece on disk not valid. " \
316 | "Clearing."
317 | )
318 | piece.clear()
319 | self._pieces[piece_hash] = piece
320 | return self._pieces
321 |
322 | @property
323 | def save_directory(self):
324 | """
325 | Return path for where the files should go.
326 | """
327 | return os.path.join(self.save_path, self.name)
328 |
329 | @property
330 | def piece_directory(self):
331 | """
332 | Return path for where pieces should go.
333 | """
334 | return os.path.join(self.save_directory, self.PIECE_DIR)
335 |
336 | def run(self):
337 | """
338 | Just download the torrent. No messing.
339 | """
340 | self.create_directory()
341 | while True:
342 | try:
343 | for peer in self.peers.values()[:self.MAX_PEERS]:
344 | if peer.status == peer.ESTATUS.NOT_STARTED or \
345 | peer.status == peer.ESTATUS.CLOSED:
346 | peer.run()
347 | logging.info("Handshake OK. Client ID: " \
348 | "{client}".format(
349 | client = peer.client
350 | )
351 | )
352 | peer.handle_message() # should be bitfield
353 |
354 | # not a smart way to select pieces
355 | piece = choice(filter(
356 | lambda piece: not piece.valid, self.pieces.values()
357 | ))
358 | logging.info("Piece {sha} selected".format(
359 | sha=piece.hex
360 | ))
361 | peer = choice(filter(
362 | lambda peer:
363 | peer.pieces[piece.sha].have and not \
364 | peer.status == peer.ESTATUS.CHOKE,
365 | self.peers.values()
366 | ))
367 | logging.info("Peer {host} selected".format(
368 | host=peer.hostport[0]
369 | ))
370 | piece.complete(peer.acquire(piece))
371 | piece_path = piece.piece_path(self.piece_directory)
372 | logging.info("Piece complete. Saving to: {0}".format(
373 | piece_path
374 | ))
375 | with open(piece_path, "wb") as f:
376 | piece.save(f)
377 |
378 |
379 | if self.complete:
380 | self.split_out()
381 |
382 | self.advertise_piece(piece)
383 |
384 | except BitTorrentPeerException as e:
385 | logging.warning("Peer {host} disconnected".format(
386 | host=peer.hostport[0]
387 | ))
388 | logging.debug("Disconnected because: {e}".format(e=e))
389 | self.clean_peers()
390 |
391 | def advertise_piece(self, piece):
392 | """
393 | For all peers let them know I now have this piece.
394 | :param piece: `class Piece` object
395 | """
396 | index = self.pieces.values().index(piece)
397 | for peer in self.peers.values():
398 | if peer.status == peer.ESTATUS.OK:
399 | peer.send_have(index)
400 |
401 | def split_out(self):
402 | """
403 | For all the files in the torrent, get the pieces and create the
404 | files.
405 | """
406 | extra_data = ""
407 | for file_name, size in self.files.items():
408 | size_count = 0
409 | file_path = os.path.join(
410 | self.save_directory,
411 | file_name
412 | )
413 | self.make_file_path(file_path)
414 | with open(file_path, "wb") as f:
415 | f.write(extra_data) # if any
416 | for piece in self.pieces:
417 | size_count += len(piece.data)
418 | if size_count > size:
419 | overrun = size_count - size
420 | data = piece.data[:overrun]
421 | extra_data = piece.data[overrun:]
422 | else:
423 | data = piece.data
424 |
425 | def make_file_path(self, file_path):
426 | """
427 | Create any necessary sub directories for torrent files
428 | :path file_path: directory to make
429 | """
430 | file_dir = os.path.dirname(file_path)
431 | if file_dir is not "" and not os.path.exists(file_dir):
432 | os.makedirs(file_dir)
433 |
434 | def create_directory(self):
435 | """
436 | Create directory for files to be saved in
437 | """
438 | if not self.save_directory.startswith(self.save_path):
439 | raise RuntimeError(
440 | "Torrent name innappropriately naviages directories. " \
441 | "Resulting path: {0}".format(path)
442 | )
443 | if not os.path.isdir(self.save_directory):
444 | try:
445 | os.mkdir(self.save_directory)
446 | except OSError as e:
447 | raise BitTorrentException("Cannot create path '{0}'. " \
448 | "Does base path exist?".format(e))
449 |
450 | if not os.path.isdir(self.piece_directory):
451 | os.mkdir(self.piece_directory)
452 |
453 | def clean_peers(self):
454 | """
455 | Look for any peers in `self.peers` that have had their
456 | connections closed and remove them from the peer list.
457 | """
458 | for k, peer in self.peers.items():
459 | if peer.status == peer.ESTATUS.CLOSED:
460 | del self._peers[k]
461 |
462 |
463 | class TorrentClient(object):
464 | def __init__(self, save_path, torrents=[]):
465 | self.save_path = save_path
466 | self.torrents = []
467 |
468 | def add_torrent(self, torrent_path):
469 | self.torrents.append(Torrent.from_path(
470 | torrent_path,
471 | self.save_path
472 | ))
473 |
474 |
--------------------------------------------------------------------------------
/pythorrent/peer.py:
--------------------------------------------------------------------------------
1 | # This file is part of PYThorrent.
2 | #
3 | # PYThorrent is free software: you can redistribute it and/or modify
4 | # it under the terms of the GNU General Public License as published by
5 | # the Free Software Foundation, either version 3 of the License, or
6 | # (at your option) any later version.
7 | #
8 | # PYThorrent is distributed in the hope that it will be useful,
9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | # GNU General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with PYThorrent. If not, see .
15 |
16 | from datetime import timedelta, datetime
17 | from struct import unpack, pack
18 | import socket
19 | from collections import OrderedDict
20 |
21 | from bitstring import BitArray
22 |
23 | from .pieces import PieceRemote
24 | from . import BitTorrentException
25 |
26 | import logging
27 |
28 | class BitTorrentPeerException(BitTorrentException):
29 | pass
30 |
31 | class Peer(object):
32 | PIECE = PieceRemote
33 | CONNECTION_TIMEOUT = 10
34 | BLOCK_SIZE = pow(2,14)
35 | class ESTATUS:
36 | """
37 | Connection status.
38 | """
39 | BAD = -3
40 | NOT_STARTED = -2
41 | CLOSED = -1
42 | CHOKE = 0
43 | OK = 1
44 |
45 | def __init__(self, hostport, torrent):
46 | """
47 | Represents the peer you're connected to.
48 | :param hostport: tuple containing IP and port of remote client
49 | :param torrent: Torrent object representing what is being
50 | downloaded.
51 | """
52 | self.hostport = hostport
53 | self.torrent = torrent
54 | self.status = self.ESTATUS.NOT_STARTED
55 | self.reserved = None
56 | self.info_hash = None
57 | self.peer_id = None
58 | self._pieces = None
59 | self.uploaded = 0
60 | self.buff = ""
61 |
62 | @property
63 | def client(self):
64 | """
65 | Quick and dirty check to find the name of the peer's client
66 | """
67 | return self.peer_id[1:7]
68 |
69 | @property
70 | def pieces(self):
71 | """
72 | Return all the peices associated with this torrent but from the
73 | peer's perspective.
74 | Returns list of RemotePiece
75 | """
76 | if self._pieces is None:
77 | self._pieces = OrderedDict()
78 | for torrent_piece in self.torrent.pieces.values():
79 | peer_piece = self.PIECE(
80 | torrent_piece.sha,
81 | self
82 | )
83 | self._pieces[peer_piece.sha] = peer_piece
84 | return self._pieces
85 |
86 | def run(self):
87 | """
88 | Get everything in place to talk to peer
89 | """
90 | self.setup()
91 | self.handshake()
92 | self.recv_handshake()
93 |
94 | def setup(self):
95 | """
96 | Open socket with peer
97 | """
98 | self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
99 | self.conn.settimeout(self.CONNECTION_TIMEOUT)
100 | try:
101 | self.conn.connect(self.hostport)
102 | except socket.error:
103 | self.close()
104 | raise BitTorrentPeerException(
105 | "Could not connect to peer: {0}".format(self.hostport)
106 | )
107 | self.status = self.ESTATUS.OK
108 |
109 | def close(self):
110 | """
111 | Central closing function
112 | """
113 | self.status = self.ESTATUS.CLOSED
114 | self.conn.close()
115 |
116 | def bad(self):
117 | """
118 | Like the close function but marks this peer as a bad peer so
119 | that the connection does not get reopened.
120 | """
121 | self.conn.close()
122 | self.status = self.ESTATUS.BAD
123 |
124 | def send(self, message):
125 | """
126 | Send a byte string to the peer.
127 | :param message: Binary string of bytes to send
128 | """
129 | try:
130 | self.conn.sendall(message)
131 | except socket.error as e:
132 | self.close()
133 | raise BitTorrentPeerException(
134 | "Connection closed by peer when sending"
135 | )
136 |
137 | def recv(self, length):
138 | """
139 | Grab custom lengths of data rather than binary divisible, or
140 | find that we didn't get all of it.
141 | Possibly not best practice but wanted a central place to do it.
142 |
143 | :param length: Integer for much to receive and recieve from the
144 | socket.
145 | """
146 | buff = ""
147 | remaining = length
148 |
149 | while len(buff) < length:
150 | try:
151 | if remaining > 4096:
152 | recvd = self.conn.recv(4096)
153 | else:
154 | recvd = self.conn.recv(remaining)
155 | except socket.error as e:
156 | self.close()
157 | raise BitTorrentPeerException(
158 | "Connection closed by peer when receiving"
159 | )
160 | if not recvd:
161 | raise BitTorrentPeerException("Received {0} {1}".format(
162 | len(buff), remaining
163 | ))
164 | buff += recvd
165 | remaining -= len(recvd)
166 | return buff
167 |
168 | # HANDSHAKE
169 |
170 | def handshake(self):
171 | """
172 | Send handshake message
173 | """
174 | self.send(self.torrent.handshake_message)
175 |
176 | def recv_handshake(self):
177 | """
178 | Handle receiving handshake from peer
179 | """
180 | protocol_id_length = ord(self.recv(1))
181 | protocol_id = self.recv(protocol_id_length)
182 | if protocol_id != self.torrent.PROTOCOL_ID:
183 | self.bad()
184 | raise BitTorrentPeerException("Connection is not serving " \
185 | "the BitTorrent protocol. Closed connection.")
186 | self.reserved = self.recv(8)
187 | self.info_hash = self.recv(20)
188 | self.peer_id = self.recv(20)
189 |
190 | # HANDLE MESSAGES
191 |
192 | def handle_message(self):
193 | """
194 | Takes the message from the socket and processes it.
195 | """
196 | message_type, payload_length = self.handle_message_type()
197 | message_type(payload_length)
198 |
199 | def handle_message_type(self):
200 | """
201 | Takes the message header from the socket and processes it.
202 | Returns the message_type as a function and the payload length as
203 | a tuple.
204 | """
205 | message_type, payload_length = self.handle_message_header()
206 | logging.debug("Message type: {0}".format(message_type))
207 | logging.debug("Message payload length: {0}".format(
208 | payload_length
209 | ))
210 | return self.type_convert(message_type), payload_length
211 |
212 | def handle_message_header(self):
213 | """
214 | Accepts the first 5 bytes from the socket that make up the
215 | message header and returns the message type number and the
216 | length of the payload as a tuple.
217 | """
218 | payload_length = unpack(">I", self.recv(4))[0]
219 | # protection from a keep-alive
220 | if payload_length > 0:
221 | message_type = ord(self.recv(1))
222 | else:
223 | message_type = None
224 | return message_type, payload_length-1
225 |
226 | def type_convert(self, message_type):
227 | """
228 | Take an integer and translate it in to the function that can
229 | handle that message type.
230 | :param message_type: integer
231 | Returns function.
232 | """
233 | if 0 == message_type: return self.recv_choke
234 | if 1 == message_type: return self.recv_unchoke
235 | if 2 == message_type: return self.recv_interested
236 | if 3 == message_type: return self.recv_uninterested
237 | if 4 == message_type: return self.recv_have
238 | if 5 == message_type: return self.recv_bitfield
239 | if 6 == message_type: return self.recv_request
240 | if 7 == message_type: return self.recv_piece
241 | if 8 == message_type: return self.recv_cancel
242 | if 9 == message_type: return self.recv_port
243 | return self.recv_keep_alive
244 |
245 | def acquire(self, torrent_piece):
246 | """
247 | Takes a torrent piece and makes sures to get all the blocks to
248 | build that piece.
249 | :param torrent_piece: Piece object.
250 | Returns Piece if correctly downloaded or None if not downloaded
251 | """
252 | index = self.torrent.pieces.values().index(torrent_piece)
253 | peer_piece = self.pieces[torrent_piece.sha]
254 |
255 | logging.info("Sending requests for piece: {0}".format(
256 | torrent_piece.hex
257 | ))
258 | self.send_interested()
259 | next_block = peer_piece.size
260 | while next_block < self.torrent.piece_length:
261 | self.send_request(index, next_block)
262 | next_block += self.BLOCK_SIZE
263 |
264 | received = 0
265 | while not peer_piece.valid or received < self.BLOCK_SIZE:
266 | message_type, payload_len = self.handle_message_type()
267 | if message_type == self.recv_piece:
268 | received += len(message_type(payload_len))
269 | else:
270 | message_type(payload_len)
271 | logging.info("Download complete for piece: {0}".format(
272 | torrent_piece.hex
273 | ))
274 | if peer_piece.valid:
275 | return peer_piece
276 |
277 | self.bad()
278 | raise BitTorrentPeerException("Downloaded piece not valid. " \
279 | "Cut off peer."
280 | )
281 |
282 | # RECEIVE FUNCTIONS
283 |
284 | def recv_keep_alive(self, length=None):
285 | """
286 | These messages are sent to check the connection to the peer is
287 | still there.
288 | :param length: Does nothing here.
289 | """
290 | pass
291 |
292 | def recv_choke(self, length=None):
293 | """
294 | Recieved when the remote peer is over-loaded and won't handle
295 | any more messages send to it.
296 | :param length: Does nothing here.
297 | """
298 | self.status = self.ESTATUS.CHOKE
299 | payload = self.recv(length)
300 |
301 | def recv_unchoke(self, length=None):
302 | """
303 | Recieved when the remote peer has stopped being over-loaded.
304 | :param length: Does nothing here.
305 | """
306 | self.status = self.ESTATUS.OK
307 | payload = self.recv(length)
308 |
309 | def recv_interested(self, length=None):
310 | """
311 | Received when remote peer likes the look of one of your sexy
312 | pieces.
313 | :param length: Does nothing here.
314 | """
315 | payload = self.recv(length)
316 |
317 | def recv_uninterested(self, length=None):
318 | """
319 | Received when remote peer decides it can get the piece it wants
320 | from someone else :,(
321 | :param length: Does nothing here.
322 | """
323 | payload = self.recv(length)
324 |
325 | def recv_have(self, length):
326 | """
327 | Received when a peer was nice enough to tell you it has a piece
328 | you might be interested in.
329 | :param length: The size of the payload, normally a 4 byte
330 | integer
331 | """
332 | payload = self.recv(length)
333 | index = unpack(">I", payload)[0]
334 | self.pieces.values()[index].have = True
335 |
336 | def recv_bitfield(self, length):
337 | """
338 | Received only at the start of a connection when a peer wants to
339 | tell you all the pieces it has in a very compact form.
340 | :param length: The size of the payload, a number of bits
341 | representing the number of pieces
342 | """
343 | payload = self.recv(length)
344 | bits = BitArray(bytes=payload)
345 | for i in range(len(self.torrent.pieces)):
346 | sha, piece = self.torrent.pieces.items()[i]
347 | piece = self.PIECE(sha, self, have=bits[i])
348 | self.pieces[sha] = piece
349 |
350 | def recv_request(self, length):
351 | """
352 | Received when a peer wants a bit of one of your pieces.
353 | :param length: The size of the payload, a bunch of 4 byte
354 | integers representing the data the peer wants.
355 | """
356 | payload = self.recv(length)
357 | index, begin, size = unpack(">III", payload)
358 | if size > self.BLOCK_SIZE:
359 | self.bad()
360 | raise BitTorrentPeerException("Peer requested too much " \
361 | "data for a normal block: {size}".format(
362 | size=size
363 | ))
364 | data = self.pieces.values()[index].data[begin:size]
365 | self.send_piece(index, begin, data)
366 |
367 | def recv_piece(self, length):
368 | """
369 | The good stuff. Receives a block of data, not a whole piece, but
370 | makes up a part of a piece.
371 | :param length: The size of the payload, two 4 byte integers
372 | representing the position of the block, and then the block
373 | itself.
374 | """
375 | payload = self.recv(length)
376 | index, begin = unpack(">II", payload[:8])
377 | block = payload[8:]
378 | self.pieces.values()[index].insert_block(begin, block)
379 | return block
380 |
381 | def recv_cancel(self, length):
382 | """
383 | Received when a peer has made a request of a piece (or block),
384 | and you haven't yet fulfilled it, but the peer doesn't want it
385 | any more anyway.
386 | :param length: Not used here.
387 | """
388 | pass
389 |
390 | def recv_port(self, length):
391 | """
392 | Received when we're talking DHT, but for now, not used.
393 | :param length: Not used here.
394 | """
395 | payload = self.recv(length)
396 |
397 | # SEND
398 |
399 | def send_payload(self, message_type, payload=""):
400 | """
401 | Handy shortcut for sending messages.
402 | :param message_type: integer representing the message type
403 | :param payload: string of bytes of what to send
404 | """
405 | encoded_message_type = pack(">B", message_type)
406 | message_length = pack(
407 | ">I",
408 | len(payload) + len(encoded_message_type)
409 | )
410 | self.send(message_length + encoded_message_type + payload)
411 |
412 | def send_keep_alive(self):
413 | """
414 | Used to make sure the connection remains open.
415 | Doesn't use `send_payload` as it doesn't have a message type.
416 | """
417 | self.send("\x00"*4)
418 |
419 | def send_choke(self):
420 | """
421 | Tell the peer that this client can't handle any more messages
422 | and that all messages received will be ignored.
423 | """
424 | self.send_payload(0)
425 |
426 | def send_unchoke(self):
427 | """
428 | Tell a peer that it won't ignore it any more.
429 | """
430 | self.send_payload(1)
431 |
432 | def send_interested(self):
433 | """
434 | Tell the peer that you're interested in one of it's delicious
435 | pieces.
436 | """
437 | self.send_payload(2)
438 |
439 | def send_uninterested(self):
440 | """
441 | Tell the peer you've found someone better and there's plenty more
442 | fish in the sea.
443 | """
444 | self.send_payload(3)
445 |
446 | def send_have(self, index):
447 | """
448 | Tell the peer that this client now has this piece.
449 | :param index: Index of the piece you want to tell the peer is
450 | here.
451 | """
452 | payload = pack(">I", index)
453 | self.send_payload(4, payload)
454 |
455 | def send_bitfield(self):
456 | """
457 | Tell the peer all the pieces you have in a really compact form.
458 | """
459 | # the pieces are compacted in sequence in to bits
460 | field = BitArray(
461 | map(
462 | lambda sha, piece : sha == piece.digest,
463 | self.torrent.pieces.items()
464 | )
465 | )
466 | self.send_payload(5, field.tobytes())
467 |
468 | def send_request(self, index, begin, length=None):
469 | """
470 | Request a block (rather than piece) from the peer, using the
471 | location and start point of the piece. The BitTorrent protocol
472 | uses a request/send method of downloading, so this asks a peer
473 | to send me a piece. It may work, it may not.
474 | :param index: Integer index of the piece being requested.
475 | :param begin: Integer of the byte that represents the block to
476 | download.
477 | :param length: Optional integer for how much to send, can also
478 | work it out itself.
479 | """
480 | if length is None:
481 | length = self.BLOCK_SIZE
482 | payload = pack(">III", index, begin, length)
483 | self.send_payload(6, payload)
484 |
485 | def send_piece(self, index, begin, data=None):
486 | """
487 | Send a requested piece to the peer, using the location and start
488 | point of the piece. Can work out what to send itself or can send
489 | whatever you like.
490 | :param index: Integer index of the piece was requested.
491 | :param begin: Integer of the byte that represents the block to
492 | upload.
493 | """
494 | if data is None:
495 | data = self.torrent.pieces.values()[index] \
496 | [begin:self.BLOCK_SIZE]
497 | header = pack(">II", index, begin)
498 | self.send_payload(7, header + data)
499 | self.uploaded += len(data)
500 |
501 | def send_cancel(self, index, begin, length=None):
502 | """
503 | Tells the peer that any pieces that have been requested can now
504 | be ignored and not sent to this client. The index, begin, and
505 | possibly length are used as identifiers to find that request and
506 | remove it from the queue of requests.
507 | :param index: Integer index of the piece was requested.
508 | :param begin: Integer of the byte that represents the block to
509 | upload.
510 | :param length: Integer representing the size of the block that
511 | was requested. If not known, will guess.
512 | """
513 | if length is None:
514 | length = self.BLOCK_SIZE
515 | payload = pack(">III", index, begin, length)
516 | self.send_payload(8, header + payload)
517 |
518 | def send_port(self):
519 | """
520 | Send when we're talking DHT, but for now, not used.
521 | :param length: Not used here.
522 | """
523 | pass
524 |
525 |
526 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------