Browse Source

Initial import from mercurial

spaghetti 2 years ago
commit
87311840cb

+ 1
- 0
AUTHORS View File

@@ -0,0 +1 @@
1
+Robert Nitsch

+ 12
- 0
LICENSE View File

@@ -0,0 +1,12 @@
1
+This program is free software: you can redistribute it and/or modify
2
+it under the terms of the GNU General Public License as published by
3
+the Free Software Foundation, either version 3 of the License, or
4
+(at your option) any later version.
5
+
6
+This program is distributed in the hope that it will be useful,
7
+but WITHOUT ANY WARRANTY; without even the implied warranty of
8
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9
+GNU General Public License for more details.
10
+
11
+You should have received a copy of the GNU General Public License
12
+along with this program.  If not, see <http://www.gnu.org/licenses/>.

+ 153
- 0
docs/Makefile View File

@@ -0,0 +1,153 @@
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) source
14
+# the i18n builder cannot share the environment and doctrees with the others
15
+I18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
16
+
17
+.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
18
+
19
+help:
20
+	@echo "Please use \`make <target>' where <target> is one of"
21
+	@echo "  html       to make standalone HTML files"
22
+	@echo "  dirhtml    to make HTML files named index.html in directories"
23
+	@echo "  singlehtml to make a single large HTML file"
24
+	@echo "  pickle     to make pickle files"
25
+	@echo "  json       to make JSON files"
26
+	@echo "  htmlhelp   to make HTML files and a HTML help project"
27
+	@echo "  qthelp     to make HTML files and a qthelp project"
28
+	@echo "  devhelp    to make HTML files and a Devhelp project"
29
+	@echo "  epub       to make an epub"
30
+	@echo "  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
31
+	@echo "  latexpdf   to make LaTeX files and run them through pdflatex"
32
+	@echo "  text       to make text files"
33
+	@echo "  man        to make manual pages"
34
+	@echo "  texinfo    to make Texinfo files"
35
+	@echo "  info       to make Texinfo files and run them through makeinfo"
36
+	@echo "  gettext    to make PO message catalogs"
37
+	@echo "  changes    to make an overview of all changed/added/deprecated items"
38
+	@echo "  linkcheck  to check all external links for integrity"
39
+	@echo "  doctest    to run all doctests embedded in the documentation (if enabled)"
40
+
41
+clean:
42
+	-rm -rf $(BUILDDIR)/*
43
+
44
+html:
45
+	$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
46
+	@echo
47
+	@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
48
+
49
+dirhtml:
50
+	$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
51
+	@echo
52
+	@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
53
+
54
+singlehtml:
55
+	$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
56
+	@echo
57
+	@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
58
+
59
+pickle:
60
+	$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
61
+	@echo
62
+	@echo "Build finished; now you can process the pickle files."
63
+
64
+json:
65
+	$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
66
+	@echo
67
+	@echo "Build finished; now you can process the JSON files."
68
+
69
+htmlhelp:
70
+	$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
71
+	@echo
72
+	@echo "Build finished; now you can run HTML Help Workshop with the" \
73
+	      ".hhp project file in $(BUILDDIR)/htmlhelp."
74
+
75
+qthelp:
76
+	$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
77
+	@echo
78
+	@echo "Build finished; now you can run "qcollectiongenerator" with the" \
79
+	      ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
80
+	@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/py3createtorrent.qhcp"
81
+	@echo "To view the help file:"
82
+	@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/py3createtorrent.qhc"
83
+
84
+devhelp:
85
+	$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
86
+	@echo
87
+	@echo "Build finished."
88
+	@echo "To view the help file:"
89
+	@echo "# mkdir -p $$HOME/.local/share/devhelp/py3createtorrent"
90
+	@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/py3createtorrent"
91
+	@echo "# devhelp"
92
+
93
+epub:
94
+	$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
95
+	@echo
96
+	@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
97
+
98
+latex:
99
+	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
100
+	@echo
101
+	@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
102
+	@echo "Run \`make' in that directory to run these through (pdf)latex" \
103
+	      "(use \`make latexpdf' here to do that automatically)."
104
+
105
+latexpdf:
106
+	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
107
+	@echo "Running LaTeX files through pdflatex..."
108
+	$(MAKE) -C $(BUILDDIR)/latex all-pdf
109
+	@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
110
+
111
+text:
112
+	$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
113
+	@echo
114
+	@echo "Build finished. The text files are in $(BUILDDIR)/text."
115
+
116
+man:
117
+	$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
118
+	@echo
119
+	@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
120
+
121
+texinfo:
122
+	$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
123
+	@echo
124
+	@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
125
+	@echo "Run \`make' in that directory to run these through makeinfo" \
126
+	      "(use \`make info' here to do that automatically)."
127
+
128
+info:
129
+	$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
130
+	@echo "Running Texinfo files through makeinfo..."
131
+	make -C $(BUILDDIR)/texinfo info
132
+	@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
133
+
134
+gettext:
135
+	$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
136
+	@echo
137
+	@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
138
+
139
+changes:
140
+	$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
141
+	@echo
142
+	@echo "The overview file is in $(BUILDDIR)/changes."
143
+
144
+linkcheck:
145
+	$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
146
+	@echo
147
+	@echo "Link check complete; look for any errors in the above output " \
148
+	      "or in $(BUILDDIR)/linkcheck/output.txt."
149
+
150
+doctest:
151
+	$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
152
+	@echo "Testing of doctests in the sources finished, look at the " \
153
+	      "results in $(BUILDDIR)/doctest/output.txt."

+ 190
- 0
docs/make.bat View File

@@ -0,0 +1,190 @@
1
+@ECHO OFF
2
+
3
+REM Command file for Sphinx documentation
4
+
5
+if "%SPHINXBUILD%" == "" (
6
+	set SPHINXBUILD=sphinx-build
7
+)
8
+set BUILDDIR=build
9
+set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source
10
+set I18NSPHINXOPTS=%SPHINXOPTS% source
11
+if NOT "%PAPER%" == "" (
12
+	set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
13
+	set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
14
+)
15
+
16
+if "%1" == "" goto help
17
+
18
+if "%1" == "help" (
19
+	:help
20
+	echo.Please use `make ^<target^>` where ^<target^> is one of
21
+	echo.  html       to make standalone HTML files
22
+	echo.  dirhtml    to make HTML files named index.html in directories
23
+	echo.  singlehtml to make a single large HTML file
24
+	echo.  pickle     to make pickle files
25
+	echo.  json       to make JSON files
26
+	echo.  htmlhelp   to make HTML files and a HTML help project
27
+	echo.  qthelp     to make HTML files and a qthelp project
28
+	echo.  devhelp    to make HTML files and a Devhelp project
29
+	echo.  epub       to make an epub
30
+	echo.  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter
31
+	echo.  text       to make text files
32
+	echo.  man        to make manual pages
33
+	echo.  texinfo    to make Texinfo files
34
+	echo.  gettext    to make PO message catalogs
35
+	echo.  changes    to make an overview over all changed/added/deprecated items
36
+	echo.  linkcheck  to check all external links for integrity
37
+	echo.  doctest    to run all doctests embedded in the documentation if enabled
38
+	goto end
39
+)
40
+
41
+if "%1" == "clean" (
42
+	for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
43
+	del /q /s %BUILDDIR%\*
44
+	goto end
45
+)
46
+
47
+if "%1" == "html" (
48
+	%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
49
+	if errorlevel 1 exit /b 1
50
+	echo.
51
+	echo.Build finished. The HTML pages are in %BUILDDIR%/html.
52
+	goto end
53
+)
54
+
55
+if "%1" == "dirhtml" (
56
+	%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
57
+	if errorlevel 1 exit /b 1
58
+	echo.
59
+	echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
60
+	goto end
61
+)
62
+
63
+if "%1" == "singlehtml" (
64
+	%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
65
+	if errorlevel 1 exit /b 1
66
+	echo.
67
+	echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
68
+	goto end
69
+)
70
+
71
+if "%1" == "pickle" (
72
+	%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
73
+	if errorlevel 1 exit /b 1
74
+	echo.
75
+	echo.Build finished; now you can process the pickle files.
76
+	goto end
77
+)
78
+
79
+if "%1" == "json" (
80
+	%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
81
+	if errorlevel 1 exit /b 1
82
+	echo.
83
+	echo.Build finished; now you can process the JSON files.
84
+	goto end
85
+)
86
+
87
+if "%1" == "htmlhelp" (
88
+	%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
89
+	if errorlevel 1 exit /b 1
90
+	echo.
91
+	echo.Build finished; now you can run HTML Help Workshop with the ^
92
+.hhp project file in %BUILDDIR%/htmlhelp.
93
+	goto end
94
+)
95
+
96
+if "%1" == "qthelp" (
97
+	%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
98
+	if errorlevel 1 exit /b 1
99
+	echo.
100
+	echo.Build finished; now you can run "qcollectiongenerator" with the ^
101
+.qhcp project file in %BUILDDIR%/qthelp, like this:
102
+	echo.^> qcollectiongenerator %BUILDDIR%\qthelp\py3createtorrent.qhcp
103
+	echo.To view the help file:
104
+	echo.^> assistant -collectionFile %BUILDDIR%\qthelp\py3createtorrent.ghc
105
+	goto end
106
+)
107
+
108
+if "%1" == "devhelp" (
109
+	%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
110
+	if errorlevel 1 exit /b 1
111
+	echo.
112
+	echo.Build finished.
113
+	goto end
114
+)
115
+
116
+if "%1" == "epub" (
117
+	%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
118
+	if errorlevel 1 exit /b 1
119
+	echo.
120
+	echo.Build finished. The epub file is in %BUILDDIR%/epub.
121
+	goto end
122
+)
123
+
124
+if "%1" == "latex" (
125
+	%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
126
+	if errorlevel 1 exit /b 1
127
+	echo.
128
+	echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
129
+	goto end
130
+)
131
+
132
+if "%1" == "text" (
133
+	%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
134
+	if errorlevel 1 exit /b 1
135
+	echo.
136
+	echo.Build finished. The text files are in %BUILDDIR%/text.
137
+	goto end
138
+)
139
+
140
+if "%1" == "man" (
141
+	%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
142
+	if errorlevel 1 exit /b 1
143
+	echo.
144
+	echo.Build finished. The manual pages are in %BUILDDIR%/man.
145
+	goto end
146
+)
147
+
148
+if "%1" == "texinfo" (
149
+	%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
150
+	if errorlevel 1 exit /b 1
151
+	echo.
152
+	echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
153
+	goto end
154
+)
155
+
156
+if "%1" == "gettext" (
157
+	%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
158
+	if errorlevel 1 exit /b 1
159
+	echo.
160
+	echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
161
+	goto end
162
+)
163
+
164
+if "%1" == "changes" (
165
+	%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
166
+	if errorlevel 1 exit /b 1
167
+	echo.
168
+	echo.The overview file is in %BUILDDIR%/changes.
169
+	goto end
170
+)
171
+
172
+if "%1" == "linkcheck" (
173
+	%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
174
+	if errorlevel 1 exit /b 1
175
+	echo.
176
+	echo.Link check complete; look for any errors in the above output ^
177
+or in %BUILDDIR%/linkcheck/output.txt.
178
+	goto end
179
+)
180
+
181
+if "%1" == "doctest" (
182
+	%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
183
+	if errorlevel 1 exit /b 1
184
+	echo.
185
+	echo.Testing of doctests in the sources finished, look at the ^
186
+results in %BUILDDIR%/doctest/output.txt.
187
+	goto end
188
+)
189
+
190
+:end

BIN
docs/source/_static/example1.png View File


BIN
docs/source/_static/example2.png View File


BIN
docs/source/_static/example3.png View File


+ 83
- 0
docs/source/changelog.rst View File

@@ -0,0 +1,83 @@
1
+Changelog
2
+=========
3
+
4
+Version 0.9.5
5
+-------------
6
+
7
+*Release date: 2013/06/04*
8
+
9
+* new: switch ``--md5`` to request MD5 hashes; they are now turned off by default,
10
+  resulting in a **significant performance improvement** (af745c8581de)
11
+* new: switch ``--exclude-pattern-ci`` for case-insensitive regular expressions
12
+  (1c68ad21c72f)
13
+* fixed: On Windows, the ``--exclude-pattern`` switch has not been case-sensitive
14
+  (f5c00b9eccbc)
15
+* fixed docs: installation instructions for py3bencode using ``setup.py`` (276a82e1cbc3)
16
+
17
+Version 0.9.4
18
+-------------
19
+
20
+*Release date: 2013/02/26*
21
+
22
+* new: documentation is now part of the repository, based on Sphinx (dd3d74f5cc26 and following)
23
+* fixed: UDP tracker announce urls (c639e2f8408a + 69afadea92e4)
24
+* fixed: piece count calculation (8450c6470d7f)
25
+* fixed: inconsistent number of blank lines after summary (30f870d55c56)
26
+
27
+Version 0.9.3
28
+-------------
29
+
30
+*Release date: 2010/12/13*
31
+
32
+* ! fixed: tracker abbreviations for openbittorrent fixed. **new default abbreviations:
33
+  openbt and publicbt** for openbittorrent and publicbittorrent. Note that both of them
34
+  do no more offer a http announce URL (they are pure UDP trackers now).
35
+* fixed: did not prompt the user when overwriting an existing torrent using the
36
+  -o <output directory> switch
37
+* fixed: version number was still 0.9 (now 0.9.3, of course), so it did not
38
+  identify itself correctly, e.g. when issueing "--version".
39
+
40
+Version 0.9.2
41
+-------------
42
+
43
+*Release date: 2010/11/09*
44
+
45
+* fixed: the private switch (--private / -P) did not have any effect (reported by steven)
46
+* fixed: wrong email address (now ...+dev@gmail.com instead of dev+...@gmail.com)
47
+
48
+Version 0.9.1
49
+-------------
50
+
51
+*Release date: 2010/10/17*
52
+
53
+* !!! fixed: torrents for single files could not be created (reported by JWA)
54
+
55
+Version 0.9
56
+-----------
57
+
58
+*Release date: 2010/08/19*
59
+
60
+* !!! fixed: creating torrents with multiple trackers did not work. the announce-list
61
+  has been created in a wrong way by version 0.8.
62
+* added: possibility to create tracker abbreviations. by default there is 'obt'
63
+  for OBT((Open BitTorrent - an open tracker project))'s announce urls
64
+* added: print summary after writing the torrent file
65
+* added: skipping symlinks that point to files or directories that have already
66
+  been processed (or are still being processed)
67
+* added: -v / --verbose option (reports skipped & processed files)
68
+* added: -q / --quiet option (at the moment this option only removes the summary
69
+  in the end)
70
+* added: you may now use --exclude-pattern to exclude files/folders based on
71
+  regular expressions
72
+* changed: applied `Python Style Guide (PEP 8) <http://www.python.org/dev/peps/pep-0008/>`_
73
+* changed: using ``#!/usr/bin/env python3`` instead of ``#!/usr/bin/python3``
74
+* changed: removed the huge get_size function, there was a better way to go
75
+* fixed: removing duplicate trackers now
76
+* fixed: empty comment now disables comment field (didn't work before)
77
+
78
+Version 0.8
79
+-----------
80
+
81
+*Release date: 2010/08/10.*
82
+
83
+Initial release.

+ 242
- 0
docs/source/conf.py View File

@@ -0,0 +1,242 @@
1
+# -*- coding: utf-8 -*-
2
+#
3
+# py3createtorrent documentation build configuration file, created by
4
+# sphinx-quickstart on Tue Feb 05 20:02:21 2013.
5
+#
6
+# This file is execfile()d with the current directory set to its containing dir.
7
+#
8
+# Note that not all possible configuration values are present in this
9
+# autogenerated file.
10
+#
11
+# All configuration values have a default; values that are commented out
12
+# serve to show the default.
13
+
14
+import sys, os
15
+
16
+# If extensions (or modules to document with autodoc) are in another directory,
17
+# add these directories to sys.path here. If the directory is relative to the
18
+# documentation root, use os.path.abspath to make it absolute, like shown here.
19
+sys.path.insert(0, os.path.abspath('../../src'))
20
+
21
+# -- General configuration -----------------------------------------------------
22
+
23
+# If your documentation needs a minimal Sphinx version, state it here.
24
+#needs_sphinx = '1.0'
25
+
26
+# Add any Sphinx extension module names here, as strings. They can be extensions
27
+# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
28
+extensions = ['sphinx.ext.autodoc']
29
+
30
+# Add any paths that contain templates here, relative to this directory.
31
+templates_path = ['_templates']
32
+
33
+# The suffix of source filenames.
34
+source_suffix = '.rst'
35
+
36
+# The encoding of source files.
37
+#source_encoding = 'utf-8-sig'
38
+
39
+# The master toctree document.
40
+master_doc = 'index'
41
+
42
+# General information about the project.
43
+project = u'py3createtorrent'
44
+copyright = u'2013, Robert Nitsch'
45
+
46
+# The version info for the project you're documenting, acts as replacement for
47
+# |version| and |release|, also used in various other places throughout the
48
+# built documents.
49
+#
50
+# The short X.Y version.
51
+version = '1.0'
52
+# The full version, including alpha/beta/rc tags.
53
+release = '1.0.0-dev'
54
+
55
+# The language for content autogenerated by Sphinx. Refer to documentation
56
+# for a list of supported languages.
57
+#language = None
58
+
59
+# There are two options for replacing |today|: either, you set today to some
60
+# non-false value, then it is used:
61
+#today = ''
62
+# Else, today_fmt is used as the format for a strftime call.
63
+#today_fmt = '%B %d, %Y'
64
+
65
+# List of patterns, relative to source directory, that match files and
66
+# directories to ignore when looking for source files.
67
+exclude_patterns = []
68
+
69
+# The reST default role (used for this markup: `text`) to use for all documents.
70
+#default_role = None
71
+
72
+# If true, '()' will be appended to :func: etc. cross-reference text.
73
+#add_function_parentheses = True
74
+
75
+# If true, the current module name will be prepended to all description
76
+# unit titles (such as .. function::).
77
+#add_module_names = True
78
+
79
+# If true, sectionauthor and moduleauthor directives will be shown in the
80
+# output. They are ignored by default.
81
+#show_authors = False
82
+
83
+# The name of the Pygments (syntax highlighting) style to use.
84
+pygments_style = 'sphinx'
85
+
86
+# A list of ignored prefixes for module index sorting.
87
+#modindex_common_prefix = []
88
+
89
+
90
+# -- Options for HTML output ---------------------------------------------------
91
+
92
+# The theme to use for HTML and HTML Help pages.  See the documentation for
93
+# a list of builtin themes.
94
+html_theme = 'default'
95
+
96
+# Theme options are theme-specific and customize the look and feel of a theme
97
+# further.  For a list of options available for each theme, see the
98
+# documentation.
99
+#html_theme_options = {}
100
+
101
+# Add any paths that contain custom themes here, relative to this directory.
102
+#html_theme_path = []
103
+
104
+# The name for this set of Sphinx documents.  If None, it defaults to
105
+# "<project> v<release> documentation".
106
+#html_title = None
107
+
108
+# A shorter title for the navigation bar.  Default is the same as html_title.
109
+#html_short_title = None
110
+
111
+# The name of an image file (relative to this directory) to place at the top
112
+# of the sidebar.
113
+#html_logo = None
114
+
115
+# The name of an image file (within the static path) to use as favicon of the
116
+# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
117
+# pixels large.
118
+#html_favicon = None
119
+
120
+# Add any paths that contain custom static files (such as style sheets) here,
121
+# relative to this directory. They are copied after the builtin static files,
122
+# so a file named "default.css" will overwrite the builtin "default.css".
123
+html_static_path = ['_static']
124
+
125
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
126
+# using the given strftime format.
127
+#html_last_updated_fmt = '%b %d, %Y'
128
+
129
+# If true, SmartyPants will be used to convert quotes and dashes to
130
+# typographically correct entities.
131
+#html_use_smartypants = True
132
+
133
+# Custom sidebar templates, maps document names to template names.
134
+#html_sidebars = {}
135
+
136
+# Additional templates that should be rendered to pages, maps page names to
137
+# template names.
138
+#html_additional_pages = {}
139
+
140
+# If false, no module index is generated.
141
+#html_domain_indices = True
142
+
143
+# If false, no index is generated.
144
+#html_use_index = True
145
+
146
+# If true, the index is split into individual pages for each letter.
147
+#html_split_index = False
148
+
149
+# If true, links to the reST sources are added to the pages.
150
+#html_show_sourcelink = True
151
+
152
+# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
153
+#html_show_sphinx = True
154
+
155
+# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
156
+#html_show_copyright = True
157
+
158
+# If true, an OpenSearch description file will be output, and all pages will
159
+# contain a <link> tag referring to it.  The value of this option must be the
160
+# base URL from which the finished HTML is served.
161
+#html_use_opensearch = ''
162
+
163
+# This is the file name suffix for HTML files (e.g. ".xhtml").
164
+#html_file_suffix = None
165
+
166
+# Output file base name for HTML help builder.
167
+htmlhelp_basename = 'py3createtorrentdoc'
168
+
169
+
170
+# -- Options for LaTeX output --------------------------------------------------
171
+
172
+latex_elements = {
173
+# The paper size ('letterpaper' or 'a4paper').
174
+#'papersize': 'letterpaper',
175
+
176
+# The font size ('10pt', '11pt' or '12pt').
177
+#'pointsize': '10pt',
178
+
179
+# Additional stuff for the LaTeX preamble.
180
+#'preamble': '',
181
+}
182
+
183
+# Grouping the document tree into LaTeX files. List of tuples
184
+# (source start file, target name, title, author, documentclass [howto/manual]).
185
+latex_documents = [
186
+  ('index', 'py3createtorrent.tex', u'py3createtorrent Documentation',
187
+   u'Robert Nitsch', 'manual'),
188
+]
189
+
190
+# The name of an image file (relative to this directory) to place at the top of
191
+# the title page.
192
+#latex_logo = None
193
+
194
+# For "manual" documents, if this is true, then toplevel headings are parts,
195
+# not chapters.
196
+#latex_use_parts = False
197
+
198
+# If true, show page references after internal links.
199
+#latex_show_pagerefs = False
200
+
201
+# If true, show URL addresses after external links.
202
+#latex_show_urls = False
203
+
204
+# Documents to append as an appendix to all manuals.
205
+#latex_appendices = []
206
+
207
+# If false, no module index is generated.
208
+#latex_domain_indices = True
209
+
210
+
211
+# -- Options for manual page output --------------------------------------------
212
+
213
+# One entry per manual page. List of tuples
214
+# (source start file, name, description, authors, manual section).
215
+man_pages = [
216
+    ('index', 'py3createtorrent', u'py3createtorrent Documentation',
217
+     [u'Robert Nitsch'], 1)
218
+]
219
+
220
+# If true, show URL addresses after external links.
221
+#man_show_urls = False
222
+
223
+
224
+# -- Options for Texinfo output ------------------------------------------------
225
+
226
+# Grouping the document tree into Texinfo files. List of tuples
227
+# (source start file, target name, title, author,
228
+#  dir menu entry, description, category)
229
+texinfo_documents = [
230
+  ('index', 'py3createtorrent', u'py3createtorrent Documentation',
231
+   u'Robert Nitsch', 'py3createtorrent', 'One line description of project.',
232
+   'Miscellaneous'),
233
+]
234
+
235
+# Documents to append as an appendix to all manuals.
236
+#texinfo_appendices = []
237
+
238
+# If false, no module index is generated.
239
+#texinfo_domain_indices = True
240
+
241
+# How to display URL addresses: 'footnote', 'no', or 'inline'.
242
+#texinfo_show_urls = 'footnote'

+ 25
- 0
docs/source/developer.rst View File

@@ -0,0 +1,25 @@
1
+Developer documentation
2
+=======================
3
+
4
+Todo
5
+----
6
+
7
+* use configuration files instead of requiring users to edit the script
8
+* add the ability to define how the announce-list should be constructed in detail
9
+  (tracker tiers etc., see `Multitracker Metadata
10
+  Extension <http://bittorrent.org/beps/bep_0012.html>`_)
11
+* add webseed support (`Hoffman style <http://bittorrent.org/beps/bep_0017.html>`_ &
12
+  `GetRight style <http://bittorrent.org/beps/bep_0019.html>`_)
13
+* improve behaviour when detecting the need for overwriting an existing torrent
14
+  (if the user aborts, the torrent has to be calculated again)
15
+* isn't the comment field supposed to be multi-lined?
16
+* create test cases, unit tests, ...
17
+* provide more examples in the documentation
18
+
19
+Future
20
+------
21
+
22
+Some ideas regarding the long-term future:
23
+
24
+* create GUI
25
+* make it possible to edit existing torrents

+ 24
- 0
docs/source/index.rst View File

@@ -0,0 +1,24 @@
1
+.. py3createtorrent documentation master file, created by
2
+   sphinx-quickstart on Tue Feb 05 20:02:21 2013.
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 py3createtorrent's documentation!
7
+============================================
8
+
9
+Contents:
10
+
11
+.. toctree::
12
+   :maxdepth: 2
13
+
14
+   user
15
+   changelog
16
+   developer
17
+
18
+Indices and tables
19
+==================
20
+
21
+* :ref:`genindex`
22
+* :ref:`modindex`
23
+* :ref:`search`
24
+

+ 410
- 0
docs/source/user.rst View File

@@ -0,0 +1,410 @@
1
+py3createtorrent
2
+================
3
+
4
+*Create torrents via command line!*
5
+
6
+py3createtorrent is a comprehensive shell/commandline utility for creating
7
+torrents (Linux & Windows). It's a GPL-licensed Python v3.1 script. I tested it
8
+with Ubuntu 8.04 / rTorrent and Windows 7 / µTorrent.
9
+
10
+Some of the features:
11
+
12
+* you can create **huge torrents** for any amount of data
13
+* you can add a **comment** to the torrent file
14
+* you can create **private torrents** (disabled DHT, ...)
15
+* you can create torrents with **multiple trackers**
16
+* you can **exclude specific files/folders**
17
+* you can exclude files/folders based on **regular expressions**
18
+* you can specify **custom piece sizes**
19
+* you can specify custom creation dates
20
+
21
+Motivation
22
+----------
23
+
24
+There already is rTorrent, but unfortunately it does not support creating torrents.
25
+Thus, it is often a pain to seed torrents from your servers directly.
26
+
27
+py3createtorrent is intended to fill this gap.
28
+
29
+Requirements
30
+------------
31
+
32
+py3createtorrent requires at least Python 3.1 and the `py3bencode <https://bitbucket.org/rsnitsch/py3bencode>`_ module.
33
+
34
+Installation
35
+------------
36
+
37
+Download the desired version from here:
38
+https://bitbucket.org/rsnitsch/py3createtorrent/downloads
39
+
40
+The required py3bencode module is shipped alongside py3createtorrent. As long
41
+as you extract py3bencode into the same directory as the py3createtorrent script,
42
+you should be fine. This is the easy way and should be appropriate for the
43
+majority of users.
44
+
45
+Installing the py3bencode module globally
46
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
47
+
48
+Advanced users might prefer to install the py3bencode module globally in their
49
+Python installation.
50
+
51
+You can use `pip <http://www.pip-installer.org/>`_ to install the py3bencode
52
+module in your Python installation (in the site-packages, to be precise)::
53
+
54
+   pip install hg+https://bitbucket.org/rsnitsch/py3bencode
55
+
56
+Make sure to use the pip executable that belongs to the Python interpreter
57
+with which you will execute py3createtorrent.
58
+
59
+If you don't have pip around (although I strongly recommend using it) you can
60
+also try to install py3bencode manually::
61
+
62
+   $ hg clone https://bitbucket.org/rsnitsch/py3bencode
63
+   $ cd py3bencode
64
+   $ python3 setup.py install
65
+
66
+Note that any local version of py3bencode will take precedence over the global
67
+version installed in your site-packages. Thus, you will have to delete the
68
+py3bencode module that has been shipped alongside py3createtorrent, if you want
69
+the global version to be used.
70
+
71
+.. _configuration:
72
+
73
+Configuration
74
+-------------
75
+
76
+There is a small configuration section in the script (at the top):
77
+
78
+.. literalinclude:: ../../src/py3createtorrent.py
79
+   :start-after: # #############
80
+   :end-before: # ##############
81
+   :prepend: # #############
82
+   :append: # ##############
83
+
84
+Tracker abbreviations
85
+^^^^^^^^^^^^^^^^^^^^^
86
+
87
+Tracker abbrevations allow you to specify one or more tracker URLs with a single
88
+word, like 'openbt' in the default configuration. They add a lot of convenience,
89
+e.g. look at this neat & clear command::
90
+
91
+   C:\Users\Robert\Desktop\Python\createtorrent>py3createtorrent.py example openbt publicbt
92
+   Successfully created torrent:
93
+     Name:             example
94
+    (...)
95
+     Primary tracker:  udp://tracker.openbittorrent.com/announce
96
+     Backup trackers:
97
+       udp://tracker.publicbt.com:80/announce
98
+
99
+In this case, py3createtorrent recognizes the tracker abbreviations 'openbt' and
100
+'publicbt' and automatically inserts the according tracker announce URLs.
101
+
102
+.. note::
103
+
104
+   Single abbreviations may be replaced by multiple tracker announce URLs. This
105
+   way you can also create sort of "tracker groups" for different kinds of
106
+   torrents.
107
+
108
+   Example configuration::
109
+
110
+      TRACKER_ABBR = {'mytrackergroup':  ['udp://tracker.openbittorrent.com:80/announce',
111
+                                          'udp://tracker.publicbt.com:80/announce'],
112
+                      'openbt':          'udp://tracker.openbittorrent.com:80/announce',
113
+                      'publicbt':        'udp://tracker.publicbt.com:80/announce'}
114
+
115
+   Just specify lists of announce URLs instead of a single announce URL to define
116
+   such groups.
117
+
118
+Advertise setting
119
+^^^^^^^^^^^^^^^^^
120
+
121
+The ``ADVERTISE`` setting defines whether py3createtorrent is allowed to advertise
122
+itself through the comment field, if the user hasn't specified a comment.
123
+
124
+If you want to disable advertising for a single torrent only, you can use the
125
+``--comment`` option to specify an empty comment::
126
+
127
+   $ py3createtorrent.py --comment "" ...
128
+
129
+   or
130
+
131
+   $ py3createtorrent.py -c "" ...
132
+
133
+py3createtorrent will not advertise itself in this case, because you explicitly
134
+specified the empty comment.
135
+
136
+Usage
137
+-----
138
+
139
+Syntax::
140
+
141
+   Usage: py3createtorrent.py [options] <file-or-directory> <main-tracker-url> [<backup-tracker-url> ...]
142
+
143
+   py3createtorrent is a comprehensive command line utility for creating
144
+   torrents.
145
+
146
+   Options:
147
+     --version             show program's version number and exit
148
+     -h, --help            show this help message and exit
149
+     -p PIECE_LENGTH, --piece-length=PIECE_LENGTH
150
+                           piece size in KiB. 0 = automatic selection (default).
151
+     -P, --private         create private torrent
152
+     -c COMMENT, --comment=COMMENT
153
+                           include comment
154
+     -f, --force           dont ask anything, just do it
155
+     -v, --verbose         verbose mode
156
+     -q, --quiet           be quiet, e.g. don't print summary
157
+     -o PATH, --output=PATH
158
+                           custom output location (directory or complete path).
159
+                           default = current directory.
160
+     -e PATH, --exclude=PATH
161
+                           exclude path (can be repeated)
162
+     --exclude-pattern=REGEXP
163
+                           exclude paths matching the regular expression (can be
164
+                           repeated)
165
+     --exclude-pattern-ci=REGEXP
166
+                           exclude paths matching the case-insensitive regular
167
+                           expression (can be repeated)
168
+     -d TIMESTAMP, --date=TIMESTAMP
169
+                           set creation date (unix timestamp). -1 = now
170
+                           (default). -2 = disable.
171
+     -n NAME, --name=NAME  use this file (or directory) name instead of the real
172
+                           one
173
+     --md5                 include MD5 hashes in torrent file
174
+
175
+Piece size (``-p``)
176
+^^^^^^^^^^^^^^^^^^^
177
+
178
+This switch allows you to specify a custom piece size. The piece size should be
179
+chosen with care, because it affects the following properties:
180
+
181
+* size of the .torrent file
182
+* network overhead
183
+* cost of fixing corrupted pieces
184
+* time it takes until peers start sharing data
185
+
186
+.. note::
187
+
188
+   Unless you know what you're doing, please let py3createtorrent automatically
189
+   determine the best piece size for you.
190
+
191
+Background
192
+""""""""""
193
+
194
+In general, the files for which a .torrent is created are sliced up in **pieces**.
195
+
196
+For each piece, a 20-byte checksum (based on SHA-1, the Secure Hash Algorithm 1) is
197
+calculated and stored inside the .torrent file - this, by the way, is the
198
+time-consuming part of torrent creation. Therefore, the piece size strongly
199
+correlates with the size of the created .torrent file: The larger the pieces,
200
+the smaller the number of pieces for which a checksum must be stored (and vice
201
+versa).
202
+
203
+The piece size also affects the **network overhead** involved in the peer-2-peer
204
+communication for a torrent. The peers regularly exchange information records
205
+that specify the pieces that each peer has finished downloading so that they know
206
+where they can get certain pieces from. The greater the number of pieces, the
207
+larger these information records need to be and thus the greater the overhead
208
+will tend to be.
209
+
210
+Moreover, corrupted pieces need to be redownloaded. Of course, large pieces
211
+are more expensive to redownload (both in terms of time and traffic).
212
+
213
+Finally, the piece size also affects the time it takes until peers
214
+start to share data with each other (only pieces that have been downloaded
215
+completely can be shared with other peers). Therefore, if the piece size is
216
+large, it will take longer for any peer to finish downloading a piece and to be
217
+able to share this piece with other peers.
218
+
219
+Private torrents (``-P``)
220
+^^^^^^^^^^^^^^^^^^^^^^^^^
221
+
222
+Private torrents force the BitTorrent clients to only use the specified trackers
223
+for discovering other peers. Advanced peer discovery methods like DHT or
224
+peer list exchange are effectively disabled.
225
+
226
+Comment (``-c``)
227
+^^^^^^^^^^^^^^^^
228
+
229
+The comment is a short text stored in the .torrent file and displayed by most
230
+BitTorrent clients in the torrent info.
231
+
232
+By default py3createtorrent uses "created by py3createtorrent <version>" as
233
+comment (to change this behavior, consult the :ref:`configuration` section).
234
+
235
+Force (``-f``)
236
+^^^^^^^^^^^^^^
237
+
238
+Force makes py3createtorrent e.g. overwrite existing .torrent files without
239
+asking for your permission.
240
+
241
+Verbose (``-v``)
242
+^^^^^^^^^^^^^^^^
243
+
244
+Verbose mode makes py3createtorrent report about the individual steps it is
245
+undertaking while creating the .torrent file.
246
+
247
+This is particularly useful for debugging purposes.
248
+
249
+Quiet (``-q``)
250
+^^^^^^^^^^^^^^
251
+
252
+py3createtorrent will try to stay completely silent on the commandline.
253
+
254
+Output path (``-o``)
255
+^^^^^^^^^^^^^^^^^^^^
256
+
257
+The output path is either the directory in which the .torrent file should be
258
+saved or the complete path to the destination .torrent file. In the former
259
+case, the name of the .torrent file is deduced from the input's name (i.e.
260
+the input directory's or file's name), unless this name is explicitly
261
+overwritten (using the ``-n`` switch). (In the latter case, the name of the
262
+.torrent file is itself specified by the output path.)
263
+
264
+By default, py3createtorrent uses the current working directory as the output
265
+directory.
266
+
267
+Exclude path (``-e``)
268
+^^^^^^^^^^^^^^^^^^^^^
269
+
270
+This allows for the exclusion of specific files or directories.
271
+
272
+The switch may be used repeatedly to exclude multiple files/directories.
273
+
274
+On Windows, this is case-insensitive.
275
+
276
+Exclude pattern (``--exclude-pattern``, ``--exclude-pattern-ci``)
277
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
278
+
279
+This allows for the exclusion of files or directories that match a certain
280
+pattern (regular expression).
281
+
282
+The switches may be used repeatedly to specify multiple exclusion patterns.
283
+
284
+*New in version 0.9.5:* The ``--exclude-pattern-ci`` variant (case-insensitive).
285
+On Windows, the ``--exclude-pattern`` has been made case-sensitive (previously
286
+it was case-insensitive on Windows and case-sensitive on UNIX etc.).
287
+
288
+Creation date (``-d``)
289
+^^^^^^^^^^^^^^^^^^^^^^
290
+
291
+This switch allows you to overwrite the creation date saved in the .torrent
292
+file. You can fake any creation date you like.
293
+
294
+The creation date is specified as `UNIX timestamp
295
+<https://en.wikipedia.org/wiki/Unix_time>`_.
296
+
297
+Name (``-n``)
298
+^^^^^^^^^^^^^
299
+
300
+This setting overwrites the file or directory name stored inside the .torrent
301
+file. **Thus it affects the file or directory name that will be presented
302
+to downloaders as the real name of the data.** You can use it to avoid
303
+renaming your input data.
304
+
305
+Unless a destination .torrent file is explicitly specified (using the ``-o`` switch),
306
+this name will also be used to deduce the name of the resulting .torrent file.
307
+
308
+.. note::
309
+
310
+   The name switch is an advanced feature that most users probably don't need.
311
+   Therefore, please refrain from using this feature, unless you really know
312
+   what you're doing.
313
+
314
+   For most intents and purposes, the ``-o`` switch is probably more suitable.
315
+
316
+MD5 hashes (``--md5``)
317
+^^^^^^^^^^^^^^^^^^^^^^
318
+
319
+As of py3createtorrent 0.9.5 the calculation of MD5 hashes must be explicitly
320
+requested, because it significantly slows down the torrent creation process (and
321
+makes the torrent file a little larger, although this is probably negligible).
322
+
323
+*New in 0.9.5.*
324
+
325
+Examples
326
+--------
327
+
328
+Assume there is a folder "example" with the following contents::
329
+
330
+   example/
331
+     subfolder/
332
+       10_more_minutes_please.JPG
333
+       image.rar
334
+     anotherimage.jpg
335
+     image.zip
336
+
337
+Assume, we're currently inside the parent directory.
338
+
339
+Example 1 - from directory, no options, default behaviour
340
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
341
+
342
+**Command**::
343
+
344
+   C:\Users\Robert\Desktop\Python\createtorrent>py3createtorrent.py example udp://tracker.openbittorrent.com/announce
345
+
346
+Alternative, equivalent command using a tracker abbreviation for convenience::
347
+
348
+   C:\Users\Robert\Desktop\Python\createtorrent>py3createtorrent.py example openbt
349
+
350
+**Effect**:
351
+Creates example.torrent inside the current directory.
352
+
353
+In µTorrent it will look like this:
354
+
355
+.. image:: _static/example1.png
356
+
357
+.. note::
358
+   Please note: If you do not specify a comment yourself using the ``-c`` / ``--comment``
359
+   option, py3createtorrent will advertise itself through the comment field, as
360
+   you can see in the screenshot (Torrent Contents -> Comment: *created with
361
+   py3createtorrent v0.8*).
362
+
363
+   To change this behavior, consult the :ref:`configuration` section.
364
+
365
+Example 2 - from directory, excluding subfolders
366
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
367
+
368
+**Command**::
369
+
370
+   C:\Users\Robert\Desktop\Python\createtorrent>py3createtorrent.py -e example\subfolder example udp://tracker.openbittorrent.com/announce
371
+
372
+**Effect**:
373
+Creates example.torrent inside the current directory. example\subfolder has
374
+been excluded.
375
+
376
+.. tip::
377
+   Of course you can exclude multiple subfolders, e.g.::
378
+
379
+      py3createtorrent.py -e exclusion1 -e exclusion2 yourfolder tracker-url
380
+
381
+In µTorrent it will look like this:
382
+
383
+.. image:: _static/example2.png
384
+
385
+Example 3 - from directory, excluding files
386
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
387
+
388
+**Command**::
389
+
390
+   C:\Users\Robert\Desktop\Python\createtorrent>py3createtorrent.py -e example\anotherimage.jpg -e example\subfolder\10_more_minutes_please.JPG example udp://tracker.openbittorrent.com/announce
391
+
392
+Alternative, equivalent command using **regular expressions** instead of
393
+specifying each jpg seperately (also using a tracker abbreviation to make it
394
+even shorter)::
395
+
396
+   C:\Users\Robert\Desktop\Python\createtorrent>py3createtorrent.py --exclude-pattern "(jpg|JPG)$" example openbt
397
+
398
+**Effect**:
399
+Creates example.torrent inside the current directory. example\anotherimage.jpg
400
+and example\subfolder\10_more_minutes_please.JPG have been excluded.
401
+
402
+In µTorrent it will look like this:
403
+
404
+.. image:: _static/example3.png
405
+
406
+Creating torrents of single files
407
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
408
+
409
+It's almost the same as for creating directories, except, of course, you can't
410
+use the exclude-option anymore.

+ 674
- 0
gpl-3.0.txt View File

@@ -0,0 +1,674 @@
1
+                    GNU GENERAL PUBLIC LICENSE
2
+                       Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+                            Preamble
9
+
10
+  The GNU General Public License is a free, copyleft license for
11
+software and other kinds of works.
12
+
13
+  The licenses for most software and other practical works are designed
14
+to take away your freedom to share and change the works.  By contrast,
15
+the GNU General Public License is intended to guarantee your freedom to
16
+share and change all versions of a program--to make sure it remains free
17
+software for all its users.  We, the Free Software Foundation, use the
18
+GNU General Public License for most of our software; it applies also to
19
+any other work released this way by its authors.  You can apply it to
20
+your programs, too.
21
+
22
+  When we speak of free software, we are referring to freedom, not
23
+price.  Our General Public Licenses are designed to make sure that you
24
+have the freedom to distribute copies of free software (and charge for
25
+them if you wish), that you receive source code or can get it if you
26
+want it, that you can change the software or use pieces of it in new
27
+free programs, and that you know you can do these things.
28
+
29
+  To protect your rights, we need to prevent others from denying you
30
+these rights or asking you to surrender the rights.  Therefore, you have
31
+certain responsibilities if you distribute copies of the software, or if
32
+you modify it: responsibilities to respect the freedom of others.
33
+
34
+  For example, if you distribute copies of such a program, whether
35
+gratis or for a fee, you must pass on to the recipients the same
36
+freedoms that you received.  You must make sure that they, too, receive
37
+or can get the source code.  And you must show them these terms so they
38
+know their rights.
39
+
40
+  Developers that use the GNU GPL protect your rights with two steps:
41
+(1) assert copyright on the software, and (2) offer you this License
42
+giving you legal permission to copy, distribute and/or modify it.
43
+
44
+  For the developers' and authors' protection, the GPL clearly explains
45
+that there is no warranty for this free software.  For both users' and
46
+authors' sake, the GPL requires that modified versions be marked as
47
+changed, so that their problems will not be attributed erroneously to
48
+authors of previous versions.
49
+
50
+  Some devices are designed to deny users access to install or run
51
+modified versions of the software inside them, although the manufacturer
52
+can do so.  This is fundamentally incompatible with the aim of
53
+protecting users' freedom to change the software.  The systematic
54
+pattern of such abuse occurs in the area of products for individuals to
55
+use, which is precisely where it is most unacceptable.  Therefore, we
56
+have designed this version of the GPL to prohibit the practice for those
57
+products.  If such problems arise substantially in other domains, we
58
+stand ready to extend this provision to those domains in future versions
59
+of the GPL, as needed to protect the freedom of users.
60
+
61
+  Finally, every program is threatened constantly by software patents.
62
+States should not allow patents to restrict development and use of
63
+software on general-purpose computers, but in those that do, we wish to
64
+avoid the special danger that patents applied to a free program could
65
+make it effectively proprietary.  To prevent this, the GPL assures that
66
+patents cannot be used to render the program non-free.
67
+
68
+  The precise terms and conditions for copying, distribution and
69
+modification follow.
70
+
71
+                       TERMS AND CONDITIONS
72
+
73
+  0. Definitions.
74
+
75
+  "This License" refers to version 3 of the GNU General Public License.
76
+
77
+  "Copyright" also means copyright-like laws that apply to other kinds of
78
+works, such as semiconductor masks.
79
+
80
+  "The Program" refers to any copyrightable work licensed under this
81
+License.  Each licensee is addressed as "you".  "Licensees" and
82
+"recipients" may be individuals or organizations.
83
+
84
+  To "modify" a work means to copy from or adapt all or part of the work
85
+in a fashion requiring copyright permission, other than the making of an
86
+exact copy.  The resulting work is called a "modified version" of the
87
+earlier work or a work "based on" the earlier work.
88
+
89
+  A "covered work" means either the unmodified Program or a work based
90
+on the Program.
91
+
92
+  To "propagate" a work means to do anything with it that, without
93
+permission, would make you directly or secondarily liable for
94
+infringement under applicable copyright law, except executing it on a
95
+computer or modifying a private copy.  Propagation includes copying,
96
+distribution (with or without modification), making available to the
97
+public, and in some countries other activities as well.
98
+
99
+  To "convey" a work means any kind of propagation that enables other
100
+parties to make or receive copies.  Mere interaction with a user through
101
+a computer network, with no transfer of a copy, is not conveying.
102
+
103
+  An interactive user interface displays "Appropriate Legal Notices"
104
+to the extent that it includes a convenient and prominently visible
105
+feature that (1) displays an appropriate copyright notice, and (2)
106
+tells the user that there is no warranty for the work (except to the
107
+extent that warranties are provided), that licensees may convey the
108
+work under this License, and how to view a copy of this License.  If
109
+the interface presents a list of user commands or options, such as a
110
+menu, a prominent item in the list meets this criterion.
111
+
112
+  1. Source Code.
113
+
114
+  The "source code" for a work means the preferred form of the work
115
+for making modifications to it.  "Object code" means any non-source
116
+form of a work.
117
+
118
+  A "Standard Interface" means an interface that either is an official
119
+standard defined by a recognized standards body, or, in the case of
120
+interfaces specified for a particular programming language, one that
121
+is widely used among developers working in that language.
122
+
123
+  The "System Libraries" of an executable work include anything, other
124
+than the work as a whole, that (a) is included in the normal form of
125
+packaging a Major Component, but which is not part of that Major
126
+Component, and (b) serves only to enable use of the work with that
127
+Major Component, or to implement a Standard Interface for which an
128
+implementation is available to the public in source code form.  A
129
+"Major Component", in this context, means a major essential component
130
+(kernel, window system, and so on) of the specific operating system
131
+(if any) on which the executable work runs, or a compiler used to
132
+produce the work, or an object code interpreter used to run it.
133
+
134
+  The "Corresponding Source" for a work in object code form means all
135
+the source code needed to generate, install, and (for an executable
136
+work) run the object code and to modify the work, including scripts to
137
+control those activities.  However, it does not include the work's
138
+System Libraries, or general-purpose tools or generally available free
139
+programs which are used unmodified in performing those activities but
140
+which are not part of the work.  For example, Corresponding Source
141
+includes interface definition files associated with source files for
142
+the work, and the source code for shared libraries and dynamically
143
+linked subprograms that the work is specifically designed to require,
144
+such as by intimate data communication or control flow between those
145
+subprograms and other parts of the work.
146
+
147
+  The Corresponding Source need not include anything that users
148
+can regenerate automatically from other parts of the Corresponding
149
+Source.
150
+
151
+  The Corresponding Source for a work in source code form is that
152
+same work.
153
+
154
+  2. Basic Permissions.
155
+
156
+  All rights granted under this License are granted for the term of
157
+copyright on the Program, and are irrevocable provided the stated
158
+conditions are met.  This License explicitly affirms your unlimited
159
+permission to run the unmodified Program.  The output from running a
160
+covered work is covered by this License only if the output, given its
161
+content, constitutes a covered work.  This License acknowledges your
162
+rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+  You may make, run and propagate covered works that you do not
165
+convey, without conditions so long as your license otherwise remains
166
+in force.  You may convey covered works to others for the sole purpose
167
+of having them make modifications exclusively for you, or provide you
168
+with facilities for running those works, provided that you comply with
169
+the terms of this License in conveying all material for which you do
170
+not control copyright.  Those thus making or running the covered works
171
+for you must do so exclusively on your behalf, under your direction
172
+and control, on terms that prohibit them from making any copies of
173
+your copyrighted material outside their relationship with you.
174
+
175
+  Conveying under any other circumstances is permitted solely under
176
+the conditions stated below.  Sublicensing is not allowed; section 10
177
+makes it unnecessary.
178
+
179
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+  No covered work shall be deemed part of an effective technological
182
+measure under any applicable law fulfilling obligations under article
183
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+similar laws prohibiting or restricting circumvention of such
185
+measures.
186
+
187
+  When you convey a covered work, you waive any legal power to forbid
188
+circumvention of technological measures to the extent such circumvention
189
+is effected by exercising rights under this License with respect to
190
+the covered work, and you disclaim any intention to limit operation or
191
+modification of the work as a means of enforcing, against the work's
192
+users, your or third parties' legal rights to forbid circumvention of
193
+technological measures.
194
+
195
+  4. Conveying Verbatim Copies.
196
+
197
+  You may convey verbatim copies of the Program's source code as you
198
+receive it, in any medium, provided that you conspicuously and
199
+appropriately publish on each copy an appropriate copyright notice;
200
+keep intact all notices stating that this License and any
201
+non-permissive terms added in accord with section 7 apply to the code;
202
+keep intact all notices of the absence of any warranty; and give all
203
+recipients a copy of this License along with the Program.
204
+
205
+  You may charge any price or no price for each copy that you convey,
206
+and you may offer support or warranty protection for a fee.
207
+
208
+  5. Conveying Modified Source Versions.
209
+
210
+  You may convey a work based on the Program, or the modifications to
211
+produce it from the Program, in the form of source code under the
212
+terms of section 4, provided that you also meet all of these conditions:
213
+
214
+    a) The work must carry prominent notices stating that you modified
215
+    it, and giving a relevant date.
216
+
217
+    b) The work must carry prominent notices stating that it is
218
+    released under this License and any conditions added under section
219
+    7.  This requirement modifies the requirement in section 4 to
220
+    "keep intact all notices".
221
+
222
+    c) You must license the entire work, as a whole, under this
223
+    License to anyone who comes into possession of a copy.  This
224
+    License will therefore apply, along with any applicable section 7
225
+    additional terms, to the whole of the work, and all its parts,
226
+    regardless of how they are packaged.  This License gives no
227
+    permission to license the work in any other way, but it does not
228
+    invalidate such permission if you have separately received it.
229
+
230
+    d) If the work has interactive user interfaces, each must display
231
+    Appropriate Legal Notices; however, if the Program has interactive
232
+    interfaces that do not display Appropriate Legal Notices, your
233
+    work need not make them do so.
234
+
235
+  A compilation of a covered work with other separate and independent
236
+works, which are not by their nature extensions of the covered work,
237
+and which are not combined with it such as to form a larger program,
238
+in or on a volume of a storage or distribution medium, is called an
239
+"aggregate" if the compilation and its resulting copyright are not
240
+used to limit the access or legal rights of the compilation's users
241
+beyond what the individual works permit.  Inclusion of a covered work
242
+in an aggregate does not cause this License to apply to the other
243
+parts of the aggregate.
244
+
245
+  6. Conveying Non-Source Forms.
246
+
247
+  You may convey a covered work in object code form under the terms
248
+of sections 4 and 5, provided that you also convey the
249
+machine-readable Corresponding Source under the terms of this License,
250
+in one of these ways:
251
+
252
+    a) Convey the object code in, or embodied in, a physical product
253
+    (including a physical distribution medium), accompanied by the
254
+    Corresponding Source fixed on a durable physical medium
255
+    customarily used for software interchange.
256
+
257
+    b) Convey the object code in, or embodied in, a physical product
258
+    (including a physical distribution medium), accompanied by a
259
+    written offer, valid for at least three years and valid for as
260
+    long as you offer spare parts or customer support for that product
261
+    model, to give anyone who possesses the object code either (1) a
262
+    copy of the Corresponding Source for all the software in the
263
+    product that is covered by this License, on a durable physical
264
+    medium customarily used for software interchange, for a price no
265
+    more than your reasonable cost of physically performing this
266
+    conveying of source, or (2) access to copy the
267
+    Corresponding Source from a network server at no charge.
268
+
269
+    c) Convey individual copies of the object code with a copy of the
270
+    written offer to provide the Corresponding Source.  This
271
+    alternative is allowed only occasionally and noncommercially, and
272
+    only if you received the object code with such an offer, in accord
273
+    with subsection 6b.
274
+
275
+    d) Convey the object code by offering access from a designated
276
+    place (gratis or for a charge), and offer equivalent access to the
277
+    Corresponding Source in the same way through the same place at no
278
+    further charge.  You need not require recipients to copy the
279
+    Corresponding Source along with the object code.  If the place to
280
+    copy the object code is a network server, the Corresponding Source
281
+    may be on a different server (operated by you or a third party)
282
+    that supports equivalent copying facilities, provided you maintain
283
+    clear directions next to the object code saying where to find the
284
+    Corresponding Source.  Regardless of what server hosts the
285
+    Corresponding Source, you remain obligated to ensure that it is
286
+    available for as long as needed to satisfy these requirements.
287
+
288
+    e) Convey the object code using peer-to-peer transmission, provided
289
+    you inform other peers where the object code and Corresponding
290
+    Source of the work are being offered to the general public at no
291
+    charge under subsection 6d.
292
+
293
+  A separable portion of the object code, whose source code is excluded
294
+from the Corresponding Source as a System Library, need not be
295
+included in conveying the object code work.
296
+
297
+  A "User Product" is either (1) a "consumer product", which means any
298
+tangible personal property which is normally used for personal, family,
299
+or household purposes, or (2) anything designed or sold for incorporation
300
+into a dwelling.  In determining whether a product is a consumer product,
301
+doubtful cases shall be resolved in favor of coverage.  For a particular
302
+product received by a particular user, "normally used" refers to a
303
+typical or common use of that class of product, regardless of the status
304
+of the particular user or of the way in which the particular user
305
+actually uses, or expects or is expected to use, the product.  A product
306
+is a consumer product regardless of whether the product has substantial
307
+commercial, industrial or non-consumer uses, unless such uses represent
308
+the only significant mode of use of the product.
309
+
310
+  "Installation Information" for a User Product means any methods,
311
+procedures, authorization keys, or other information required to install
312
+and execute modified versions of a covered work in that User Product from
313
+a modified version of its Corresponding Source.  The information must
314
+suffice to ensure that the continued functioning of the modified object
315
+code is in no case prevented or interfered with solely because
316
+modification has been made.
317
+
318
+  If you convey an object code work under this section in, or with, or
319
+specifically for use in, a User Product, and the conveying occurs as
320
+part of a transaction in which the right of possession and use of the
321
+User Product is transferred to the recipient in perpetuity or for a
322
+fixed term (regardless of how the transaction is characterized), the
323
+Corresponding Source conveyed under this section must be accompanied
324
+by the Installation Information.  But this requirement does not apply
325
+if neither you nor any third party retains the ability to install
326
+modified object code on the User Product (for example, the work has
327
+been installed in ROM).
328
+
329
+  The requirement to provide Installation Information does not include a
330
+requirement to continue to provide support service, warranty, or updates
331
+for a work that has been modified or installed by the recipient, or for
332
+the User Product in which it has been modified or installed.  Access to a
333
+network may be denied when the modification itself materially and
334
+adversely affects the operation of the network or violates the rules and
335
+protocols for communication across the network.
336
+
337
+  Corresponding Source conveyed, and Installation Information provided,
338
+in accord with this section must be in a format that is publicly
339
+documented (and with an implementation available to the public in
340
+source code form), and must require no special password or key for
341
+unpacking, reading or copying.
342
+
343
+  7. Additional Terms.
344
+
345
+  "Additional permissions" are terms that supplement the terms of this
346
+License by making exceptions from one or more of its conditions.
347
+Additional permissions that are applicable to the entire Program shall
348
+be treated as though they were included in this License, to the extent
349
+that they are valid under applicable law.  If additional permissions
350
+apply only to part of the Program, that part may be used separately
351
+under those permissions, but the entire Program remains governed by
352
+this License without regard to the additional permissions.
353
+
354
+  When you convey a copy of a covered work, you may at your option
355
+remove any additional permissions from that copy, or from any part of
356
+it.  (Additional permissions may be written to require their own
357
+removal in certain cases when you modify the work.)  You may place
358
+additional permissions on material, added by you to a covered work,
359
+for which you have or can give appropriate copyright permission.
360
+
361
+  Notwithstanding any other provision of this License, for material you
362
+add to a covered work, you may (if authorized by the copyright holders of
363
+that material) supplement the terms of this License with terms:
364
+
365
+    a) Disclaiming warranty or limiting liability differently from the
366
+    terms of sections 15 and 16 of this License; or
367
+
368
+    b) Requiring preservation of specified reasonable legal notices or
369
+    author attributions in that material or in the Appropriate Legal
370
+    Notices displayed by works containing it; or
371
+
372
+    c) Prohibiting misrepresentation of the origin of that material, or
373
+    requiring that modified versions of such material be marked in
374
+    reasonable ways as different from the original version; or
375
+
376
+    d) Limiting the use for publicity purposes of names of licensors or
377
+    authors of the material; or
378
+
379
+    e) Declining to grant rights under trademark law for use of some
380
+    trade names, trademarks, or service marks; or
381
+
382
+    f) Requiring indemnification of licensors and authors of that
383
+    material by anyone who conveys the material (or modified versions of
384
+    it) with contractual assumptions of liability to the recipient, for
385
+    any liability that these contractual assumptions directly impose on
386
+    those licensors and authors.
387
+
388
+  All other non-permissive additional terms are considered "further
389
+restrictions" within the meaning of section 10.  If the Program as you
390
+received it, or any part of it, contains a notice stating that it is
391
+governed by this License along with a term that is a further
392
+restriction, you may remove that term.  If a license document contains
393
+a further restriction but permits relicensing or conveying under this
394
+License, you may add to a covered work material governed by the terms
395
+of that license document, provided that the further restriction does
396
+not survive such relicensing or conveying.
397
+
398
+  If you add terms to a covered work in accord with this section, you
399
+must place, in the relevant source files, a statement of the
400
+additional terms that apply to those files, or a notice indicating
401
+where to find the applicable terms.
402
+
403
+  Additional terms, permissive or non-permissive, may be stated in the
404
+form of a separately written license, or stated as exceptions;
405
+the above requirements apply either way.
406
+
407
+  8. Termination.
408
+
409
+  You may not propagate or modify a covered work except as expressly
410
+provided under this License.  Any attempt otherwise to propagate or
411
+modify it is void, and will automatically terminate your rights under
412
+this License (including any patent licenses granted under the third
413
+paragraph of section 11).
414
+
415
+  However, if you cease all violation of this License, then your
416
+license from a particular copyright holder is reinstated (a)
417
+provisionally, unless and until the copyright holder explicitly and
418
+finally terminates your license, and (b) permanently, if the copyright
419
+holder fails to notify you of the violation by some reasonable means
420
+prior to 60 days after the cessation.
421
+
422
+  Moreover, your license from a particular copyright holder is
423
+reinstated permanently if the copyright holder notifies you of the
424
+violation by some reasonable means, this is the first time you have
425
+received notice of violation of this License (for any work) from that
426
+copyright holder, and you cure the violation prior to 30 days after
427
+your receipt of the notice.
428
+
429
+  Termination of your rights under this section does not terminate the
430
+licenses of parties who have received copies or rights from you under
431
+this License.  If your rights have been terminated and not permanently
432
+reinstated, you do not qualify to receive new licenses for the same
433
+material under section 10.
434
+
435
+  9. Acceptance Not Required for Having Copies.
436
+
437
+  You are not required to accept this License in order to receive or
438
+run a copy of the Program.  Ancillary propagation of a covered work
439
+occurring solely as a consequence of using peer-to-peer transmission
440
+to receive a copy likewise does not require acceptance.  However,
441
+nothing other than this License grants you permission to propagate or
442
+modify any covered work.  These actions infringe copyright if you do
443
+not accept this License.  Therefore, by modifying or propagating a
444
+covered work, you indicate your acceptance of this License to do so.
445
+
446
+  10. Automatic Licensing of Downstream Recipients.
447
+
448
+  Each time you convey a covered work, the recipient automatically
449
+receives a license from the original licensors, to run, modify and
450
+propagate that work, subject to this License.  You are not responsible
451
+for enforcing compliance by third parties with this License.
452
+
453
+  An "entity transaction" is a transaction transferring control of an
454
+organization, or substantially all assets of one, or subdividing an
455
+organization, or merging organizations.  If propagation of a covered
456
+work results from an entity transaction, each party to that
457
+transaction who receives a copy of the work also receives whatever
458
+licenses to the work the party's predecessor in interest had or could
459
+give under the previous paragraph, plus a right to possession of the
460
+Corresponding Source of the work from the predecessor in interest, if
461
+the predecessor has it or can get it with reasonable efforts.
462
+
463
+  You may not impose any further restrictions on the exercise of the
464
+rights granted or affirmed under this License.  For example, you may
465
+not impose a license fee, royalty, or other charge for exercise of
466
+rights granted under this License, and you may not initiate litigation
467
+(including a cross-claim or counterclaim in a lawsuit) alleging that
468
+any patent claim is infringed by making, using, selling, offering for
469
+sale, or importing the Program or any portion of it.
470
+
471
+  11. Patents.
472
+
473
+  A "contributor" is a copyright holder who authorizes use under this
474
+License of the Program or a work on which the Program is based.  The
475
+work thus licensed is called the contributor's "contributor version".
476
+
477
+  A contributor's "essential patent claims" are all patent claims
478
+owned or controlled by the contributor, whether already acquired or
479
+hereafter acquired, that would be infringed by some manner, permitted
480
+by this License, of making, using, or selling its contributor version,
481
+but do not include claims that would be infringed only as a
482
+consequence of further modification of the contributor version.  For
483
+purposes of this definition, "control" includes the right to grant
484
+patent sublicenses in a manner consistent with the requirements of
485
+this License.
486
+
487
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+patent license under the contributor's essential patent claims, to
489
+make, use, sell, offer for sale, import and otherwise run, modify and
490
+propagate the contents of its contributor version.
491
+
492
+  In the following three paragraphs, a "patent license" is any express
493
+agreement or commitment, however denominated, not to enforce a patent
494
+(such as an express permission to practice a patent or covenant not to
495
+sue for patent infringement).  To "grant" such a patent license to a
496
+party means to make such an agreement or commitment not to enforce a
497
+patent against the party.
498
+
499
+  If you convey a covered work, knowingly relying on a patent license,
500
+and the Corresponding Source of the work is not available for anyone
501
+to copy, free of charge and under the terms of this License, through a
502
+publicly available network server or other readily accessible means,
503
+then you must either (1) cause the Corresponding Source to be so
504
+available, or (2) arrange to deprive yourself of the benefit of the
505
+patent license for this particular work, or (3) arrange, in a manner
506
+consistent with the requirements of this License, to extend the patent
507
+license to downstream recipients.  "Knowingly relying" means you have
508
+actual knowledge that, but for the patent license, your conveying the
509
+covered work in a country, or your recipient's use of the covered work
510
+in a country, would infringe one or more identifiable patents in that
511
+country that you have reason to believe are valid.
512
+
513
+  If, pursuant to or in connection with a single transaction or
514
+arrangement, you convey, or propagate by procuring conveyance of, a
515
+covered work, and grant a patent license to some of the parties
516
+receiving the covered work authorizing them to use, propagate, modify
517
+or convey a specific copy of the covered work, then the patent license
518
+you grant is automatically extended to all recipients of the covered
519
+work and works based on it.
520
+
521
+  A patent license is "discriminatory" if it does not include within
522
+the scope of its coverage, prohibits the exercise of, or is
523
+conditioned on the non-exercise of one or more of the rights that are
524
+specifically granted under this License.  You may not convey a covered
525
+work if you are a party to an arrangement with a third party that is
526
+in the business of distributing software, under which you make payment
527
+to the third party based on the extent of your activity of conveying
528
+the work, and under which the third party grants, to any of the
529
+parties who would receive the covered work from you, a discriminatory
530
+patent license (a) in connection with copies of the covered work
531
+conveyed by you (or copies made from those copies), or (b) primarily
532
+for and in connection with specific products or compilations that
533
+contain the covered work, unless you entered into that arrangement,
534
+or that patent license was granted, prior to 28 March 2007.
535
+
536
+  Nothing in this License shall be construed as excluding or limiting
537
+any implied license or other defenses to infringement that may
538
+otherwise be available to you under applicable patent law.
539
+
540
+  12. No Surrender of Others' Freedom.
541
+
542
+  If conditions are imposed on you (whether by court order, agreement or
543
+otherwise) that contradict the conditions of this License, they do not
544
+excuse you from the conditions of this License.  If you cannot convey a
545
+covered work so as to satisfy simultaneously your obligations under this
546
+License and any other pertinent obligations, then as a consequence you may
547
+not convey it at all.  For example, if you agree to terms that obligate you
548
+to collect a royalty for further conveying from those to whom you convey
549
+the Program, the only way you could satisfy both those terms and this
550
+License would be to refrain entirely from conveying the Program.
551
+
552
+  13. Use with the GNU Affero General Public License.
553
+
554
+  Notwithstanding any other provision of this License, you have
555
+permission to link or combine any covered work with a work licensed
556
+under version 3 of the GNU Affero General Public License into a single
557
+combined work, and to convey the resulting work.  The terms of this
558
+License will continue to apply to the part which is the covered work,
559
+but the special requirements of the GNU Affero General Public License,
560
+section 13, concerning interaction through a network will apply to the
561
+combination as such.
562
+
563
+  14. Revised Versions of this License.
564
+
565
+  The Free Software Foundation may publish revised and/or new versions of
566
+the GNU General Public License from time to time.  Such new versions will
567
+be similar in spirit to the present version, but may differ in detail to
568
+address new problems or concerns.
569
+
570
+  Each version is given a distinguishing version number.  If the
571
+Program specifies that a certain numbered version of the GNU General
572
+Public License "or any later version" applies to it, you have the
573
+option of following the terms and conditions either of that numbered
574
+version or of any later version published by the Free Software
575
+Foundation.  If the Program does not specify a version number of the
576
+GNU General Public License, you may choose any version ever published
577
+by the Free Software Foundation.
578
+
579
+  If the Program specifies that a proxy can decide which future
580
+versions of the GNU General Public License can be used, that proxy's
581
+public statement of acceptance of a version permanently authorizes you
582
+to choose that version for the Program.
583
+
584
+  Later license versions may give you additional or different
585
+permissions.  However, no additional obligations are imposed on any
586
+author or copyright holder as a result of your choosing to follow a
587
+later version.
588
+
589
+  15. Disclaimer of Warranty.
590
+
591
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+  16. Limitation of Liability.
601
+
602
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+SUCH DAMAGES.
611
+
612
+  17. Interpretation of Sections 15 and 16.
613
+
614
+  If the disclaimer of warranty and limitation of liability provided
615
+above cannot be given local legal effect according to their terms,
616
+reviewing courts shall apply local law that most closely approximates
617
+an absolute waiver of all civil liability in connection with the
618
+Program, unless a warranty or assumption of liability accompanies a
619
+copy of the Program in return for a fee.
620
+
621
+                     END OF TERMS AND CONDITIONS
622
+
623
+            How to Apply These Terms to Your New Programs
624
+
625
+  If you develop a new program, and you want it to be of the greatest
626
+possible use to the public, the best way to achieve this is to make it
627
+free software which everyone can redistribute and change under these terms.
628
+
629
+  To do so, attach the following notices to the program.  It is safest
630
+to attach them to the start of each source file to most effectively
631
+state the exclusion of warranty; and each file should have at least
632
+the "copyright" line and a pointer to where the full notice is found.
633
+
634
+    <one line to give the program's name and a brief idea of what it does.>
635
+    Copyright (C) <year>  <name of author>
636
+
637
+    This program is free software: you can redistribute it and/or modify
638
+    it under the terms of the GNU General Public License as published by
639
+    the Free Software Foundation, either version 3 of the License, or
640
+    (at your option) any later version.
641
+
642
+    This program is distributed in the hope that it will be useful,
643
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
645
+    GNU General Public License for more details.
646
+
647
+    You should have received a copy of the GNU General Public License
648
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
649
+
650
+Also add information on how to contact you by electronic and paper mail.
651
+
652
+  If the program does terminal interaction, make it output a short
653
+notice like this when it starts in an interactive mode:
654
+
655
+    <program>  Copyright (C) <year>  <name of author>
656
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+    This is free software, and you are welcome to redistribute it
658
+    under certain conditions; type `show c' for details.
659
+
660
+The hypothetical commands `show w' and `show c' should show the appropriate
661
+parts of the General Public License.  Of course, your program's commands
662
+might be different; for a GUI interface, you would use an "about box".
663
+
664
+  You should also get your employer (if you work as a programmer) or school,
665
+if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+For more information on this, and how to apply and follow the GNU GPL, see
667
+<http://www.gnu.org/licenses/>.
668
+
669
+  The GNU General Public License does not permit incorporating your program
670
+into proprietary programs.  If your program is a subroutine library, you
671
+may consider it more useful to permit linking proprietary applications with
672
+the library.  If this is what you want to do, use the GNU Lesser General
673
+Public License instead of this License.  But first, please read
674
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.

+ 385
- 0
src/py3bencode.py View File

@@ -0,0 +1,385 @@
1
+#!/usr/bin/env python3
2
+"""
3
+py3bencode is a new GPL-licensed Bencode module developed for Python 3.
4
+
5
+= Motivation =
6
+
7
+  There already have been some Bencode modules for Python, but I haven't
8
+  found any reliable module which works with Python 3 as well.
9
+
10
+  So I created this module from scratch.
11
+
12
+
13
+= Version & Changelog =
14
+
15
+  This is version 1.0 (initial release).
16
+
17
+  No changelog so far.
18
+
19
+
20
+= Future =
21
+
22
+  Generally it might be useful to provide more specific error messages if
23
+  anything goes wrong. However, the most common errors are already covered.
24
+
25
+
26
+= Credits =
27
+
28
+  Robert Nitsch <r.s.nitsch+dev@gmail.com> - July 2010 (Version 1.0)
29
+
30
+
31
+= License =
32
+
33
+  This program is free software: you can redistribute it and/or modify
34
+  it under the terms of the GNU General Public License as published by
35
+  the Free Software Foundation, either version 3 of the License, or
36
+  (at your option) any later version.
37
+
38
+  This program is distributed in the hope that it will be useful,
39
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
40
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
41
+  GNU General Public License for more details.
42
+
43
+  You should have received a copy of the GNU General Public License
44
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
45
+"""
46
+
47
+def _bytes(_str):
48
+    """
49
+    Convert ordinary Python string (utf-8) into byte array (should be considered
50
+    as c-string).
51
+
52
+    @rtype:   bytes
53
+    """
54
+    return bytes(str(_str), "utf-8")
55
+
56
+def _str(_bytes):
57
+    """
58
+    Attempt to decode byte array back to ordinary Python string (utf-8).
59
+
60
+    Decoding cannot be guaranteed, so be careful.
61
+
62
+    @rtype:   str, but will return the original data if it can't be interpreted as utf-8
63
+    """
64
+    try:
65
+        return _bytes.decode("utf-8")
66
+    except UnicodeDecodeError:
67
+        return _bytes
68
+
69
+def bencode(thing):
70
+    """
71
+    bencodes the given object, returning a byte array
72
+    containing the bencoded data.
73
+
74
+    Allowed object types are:
75
+    - list (list)
76
+    - dictionary (dict)
77
+    - integer (int)
78
+    - string (str)
79
+    - byte array (bytes)
80
+
81
+    Note that all strings will be converted to byte arrays during the
82
+    encoding process.
83
+
84
+    @rtype:   bytes
85
+    """
86
+    if   isinstance(thing, int):
87
+        return _bytes("i%se" % thing)
88
+
89
+    elif isinstance(thing, str):
90
+        return _bytes(str(len(_bytes(thing))) + ":" + thing)
91
+
92
+    elif isinstance(thing, bytes):
93
+        return _bytes(str(len(thing)) + ":") + thing
94
+
95
+    elif isinstance(thing, bytearray):
96
+        return bencode(bytes(thing))
97
+
98
+    elif isinstance(thing, list):
99
+        return b"l" + b"".join([bencode(i) for i in thing]) + b"e"
100
+
101
+    elif isinstance(thing, dict):
102
+        result = b"d"
103
+
104
+        keys = list(thing.keys())
105
+        keys.sort()
106
+
107
+        for key in keys:
108
+            result += bencode(key) + bencode(thing[key])
109
+
110
+        return result + b"e"
111
+
112
+    raise TypeError("bencoding objects of type %s not supported" % type(thing))
113
+
114
+def bdecode(data, decode_strings=True, strict=False):
115
+    """
116
+    Restores/decodes bencoded data. The bencoded data must be given as byte array.
117
+
118
+    Note that all bencode-strings are treated as byte arrays first. Unless
119
+    decode_strings=False the bdecoder then tries to convert every byte array
120
+    to an ordinary Python string, that means: it tries to interpret every
121
+    byte string as utf-8 string.
122
+
123
+    This behavior is meant to make this module more convenient.
124
+    Though I strongly recommend to disable the automatic decoding attempts of
125
+    strings. Your application should know which bencode-strings are meant to
126
+    be utf-8 and which not.
127
+
128
+    The strict parameter enforces additional bencode conventions, these are:
129
+    - no negative zeroes are allowed for integers
130
+    - no leading  zeroes are allowed for integers
131
+
132
+    strict=False (default) means the decoder will just ignore glitches like that.
133
+    Please note that a proper encoder will never produce errors like these at all.
134
+
135
+    @rtype:   list, dict, int, str or bytes
136
+    """
137
+    if not isinstance(data, bytes):
138
+        raise TypeError("bdecode expects byte array.")
139
+
140
+    return BDecoder(data, decode_strings, strict).decode()
141
+
142
+class DecodingException(Exception):
143
+    """
144
+    Raised by the decoder on error.
145
+    """
146
+    pass
147
+
148
+class BDecoder(object):
149
+    """
150
+    The decoder itself.
151
+
152
+    See bdecode() for how to use it. (Though I recommend not to do so.)
153
+    """
154
+    def __init__(self, data, decode_strings, strict):
155
+        self.data   = data
156
+        self.pos    = 0
157
+
158
+        self.strict         = strict
159
+        self.decode_strings = decode_strings
160
+
161
+    def get_pos_char(self):
162
+        """
163
+        Get char (byte) at current position.
164
+        """
165
+        _res = self.data[self.pos:self.pos+1]
166
+
167
+        # why use slice syntax instead of ordinary random access?
168
+        # because self.data[some_index] would return a byte,
169
+        # that is a number between 0-255.
170
+        #
171
+        # slice syntax, however, returns e.g. b'A' (instead of 65).
172
+
173
+        if len(_res) == 0:
174
+            raise DecodingException("Unexpected end of data. Unterminated list/dictionary?")
175
+        return _res
176
+    pos_char = property(get_pos_char)
177
+
178
+    def decode(self):
179
+        """Decode whatever we find at the current position."""
180
+        _pos_char  =  self.pos_char
181
+
182
+        if   _pos_char == b'i':
183
+            self.pos  +=  1
184
+            return self.decode_int()
185
+        elif _pos_char == b'l':
186
+            self.pos  +=  1
187
+            return self.decode_list()
188
+        elif _pos_char == b'd':
189
+            self.pos  +=  1
190
+            return self.decode_dict()
191
+        elif _pos_char.isdigit():
192
+            return self.decode_string()
193
+        else:
194
+            raise DecodingException
195
+
196
+    def decode_int(self):
197
+        _start = self.pos
198
+        _end   = self.data.index(b'e', _start)
199
+
200
+        if _start == _end:
201
+            raise DecodingException("Empty integer.")
202
+
203
+        self.pos = _end+1
204
+
205
+        _int = int(self.data[_start:_end])
206
+
207
+        # strict: forbig leading zeroes and negative zero
208
+        if self.strict:
209
+            if bytes(str(_int), "utf-8") != self.data[_start:_end]:
210
+                raise DecodingException("Leading zeroes or negative zero detected.")
211
+
212
+        return _int
213
+
214
+    def decode_list(self):
215
+        _list = []
216
+
217
+        while True:
218
+            if self.pos_char == b'e':
219
+                self.pos += 1
220
+                return _list
221
+
222
+            _pos = self.pos
223
+
224
+            try:
225
+                _list.append(self.decode())
226
+            except DecodingException:
227
+                # did the exception happen because there is nothing to decode?
228
+                if _pos == self.pos:
229
+                    raise DecodingException("Unterminated list (or invalid list contents).")
230
+                else:
231
+                    raise
232
+
233
+        assert False
234
+
235
+    def decode_dict(self):
236
+        _dict = {}
237
+
238
+        while True:
239
+            if self.pos_char == b'e':
240
+                self.pos += 1
241
+                return _dict
242
+
243
+            if not self.pos_char.isdigit():
244
+                raise DecodingException("Invalid dictionary key (must be string).")
245
+
246
+            key        = self.decode_string()
247
+            _dict[key] = self.decode()
248
+
249
+        assert False
250
+
251
+    def decode_string(self):
252
+        _start = self.pos
253
+        _colon = self.data.index(b':', _start)
254
+        _len   = int(self.data[_start:_colon])
255
+
256
+        if _len < 0:
257
+            raise DecodingException("String with length < 0 found.")
258
+
259
+        self.pos = _colon+1+_len
260
+
261
+        _res = self.data[_colon+1:_colon+1+_len]
262
+
263
+        if self.decode_strings:
264
+            return _str(_res)
265
+        else:
266
+            return _res
267
+
268
+
269
+if __name__ == '__main__':
270
+    import sys, os
271
+
272
+    if len(sys.argv) == 2:
273
+        file = sys.argv[1]
274
+
275
+        if not os.path.isfile(file):
276
+            print("Error: '%s' is not a valid file." % file)
277
+            sys.exit(1)
278
+
279
+        with open(file, "rb") as fh:
280
+            from pprint import pprint
281
+            pprint(bdecode(fh.read()))
282
+
283
+        sys.exit(0)
284
+
285
+    ##################
286
+    # RUN UNIT TESTS #
287
+    import unittest
288
+
289
+    class Test(unittest.TestCase):
290
+        def setUp(self):
291
+            pass
292
+
293
+        def test_complex(self):
294
+            # Complex tests with a lot of hierarchy in the data.
295
+            test_data = [{'bar': 'spam', 'foo': 42},
296
+                         {'foo': ['bar', [42, 'morespam'], 'spam']},
297
+                         'gedons']
298
+
299
+            for data in test_data:
300
+                self.assertEqual(data, bdecode(bencode(data)))
301
+
302
+            # all together
303
+            self.assertEqual(test_data, bdecode(bencode(test_data)))
304
+
305
+        def test_single_ints(self):
306
+            # Testing with integers only.
307
+            test_data = [-1337, 0, 1337**2, 2**33]
308
+            for data in test_data:
309
+                self.assertEquals(data, bdecode(bencode(data)))
310
+
311
+        def test_single_strings_decoding(self):
312
+            # Testing with strings only, automatic decoding enabled (the default).
313
+            test_data = ["", "test", "utf8-string: äöü"]
314
+            for data in test_data:
315
+                self.assertEquals(data, bdecode(bencode(data)))
316
+
317
+        def test_single_strings_nodecoding(self):
318
+            # same like above but without internal decoding attempts
319
+            # (decode_strings = False)
320
+            test_data = ["", "test", "utf8-string: äöü"]
321
+            for data in test_data:
322
+                self.assertEquals(data,
323
+                                  bdecode(bencode(data),
324
+                                          decode_strings=False).decode("utf-8"))
325
+
326
+        def test_single_strings_more(self):
327
+            # decoding b"test" will result in "test" due
328
+            # to string decoding, which is activated by default
329
+            self.assertEquals("test",  bdecode(bencode(b"test")))
330
+
331
+            # decoding b"test" will result in b"test"
332
+            # if the string decoding gets disabled explicitly
333
+            self.assertEquals(b"test", bdecode(bencode(b"test"), decode_strings=False))
334
+
335
+            # however, if string decoding gets disabled explicility,
336
+            # even "test" will not be restored. instead, b"test" will be
337
+            # returned.
338
+            self.assertEquals(b"test", bdecode(bencode("test"), decode_strings=False))
339
+
340
+        def test_empty_list(self):
341
+            self.assertEquals([], bdecode(bencode([])))
342
+
343
+        def test_empty_dict(self):
344
+            self.assertEquals({}, bdecode(bencode({})))
345
+
346
+        def test_detect_bad_dict_keys(self):
347
+            with self.assertRaisesRegexp(DecodingException,
348
+                                         "^Invalid dictionary key"):
349
+                bdecode(b"di123e4:spame")
350
+
351
+        def test_detect_unterminated_list(self):
352
+            with self.assertRaisesRegexp(DecodingException,
353
+                                         "^Unexpected end of data"):
354
+                bdecode(b"li123e")
355
+
356
+        def test_detect_empty_integer(self):
357
+            with self.assertRaisesRegexp(DecodingException,
358
+                                         "^Empty integer"):
359
+                bdecode(b"l4:spamiee")
360
+
361
+        def test_detect_leading_zeroes(self):
362
+            # Detect leading zero
363
+            with self.assertRaisesRegexp(DecodingException,
364
+                                         "^Leading zeroes"):
365
+                bdecode(b"i01e", strict=True)
366
+
367
+            # Detect leading zero of negative number
368
+            with self.assertRaisesRegexp(DecodingException,
369
+                                         "^Leading zeroes"):
370
+                bdecode(b"i-01e", strict=True)
371
+
372
+            # Detect negative zero
373
+            with self.assertRaisesRegexp(DecodingException,
374
+                                         "negative zero"):
375
+                bdecode(b"i-0e", strict=True)
376
+
377
+            # However, the zero itself must be accepted...
378
+            self.assertEquals(0, bdecode(b"i0e", strict=True))
379
+
380
+        def test_bad_sized_string(self):
381
+            with self.assertRaises(DecodingException):
382
+                bdecode(b"l12:normalstring-5:badstringe")
383
+
384
+    unittest.main(testRunner=unittest.TextTestRunner(verbosity=2), exit=False)
385
+

+ 820
- 0
src/py3createtorrent.py View File

@@ -0,0 +1,820 @@
1
+#!/usr/bin/env python3
2
+"""
3
+Create torrents via command line!
4
+
5
+Copyright (C) 2010-2013 Robert Nitsch
6
+Licensed according to GPL v3.
7
+"""
8
+
9
+import datetime
10
+import hashlib
11
+import math
12
+import optparse
13
+import os
14
+import re
15
+import sys
16
+import time
17
+
18
+from py3bencode import bencode
19
+
20
+__all__ = ['calculate_piece_length',
21
+           'get_files_in_directory',
22
+           'sha1_20',
23
+           'split_path']
24
+
25
+# #############
26
+# CONFIGURATION
27
+
28
+# configure your tracker abbreviations here
29
+TRACKER_ABBR = {'openbt':       'udp://tracker.openbittorrent.com:80',
30
+                'publicbt':     'udp://tracker.publicbt.com:80'}
31
+
32
+# whether or not py3createtorrent is allowed to advertise itself
33
+# through the torrents' comment fields
34
+ADVERTISE = True
35
+
36
+# /CONFIGURATION
37
+# ##############
38
+
39
+# do not touch anything below this line unless you know what you're doing!
40
+
41
+
42
+VERSION =   '1.0.0-dev'
43
+
44
+# Note:
45
+#  Kilobyte = kB  = 1000 Bytes
46
+#  Kibibyte = KiB = 1024 Bytes  << used by py3createtorrent
47
+KIB = 2**10
48
+MIB = KIB * KIB
49
+
50
+
51
+VERBOSE = False
52
+def printv(*args, **kwargs):
53
+    """If VERBOSE is True, act as an alias for print. Else do nothing."""
54
+    if VERBOSE:
55
+        print(*args, **kwargs)
56
+
57
+def sha1_20(data):
58
+    """Return the first 20 bytes of the given data's SHA-1 hash."""
59
+    m = hashlib.sha1()
60
+    m.update(data)
61
+    return m.digest()[:20]
62
+
63
+def create_single_file_info(file, piece_length, include_md5=True):
64
+    """
65
+    Return dictionary with the following keys:
66
+      - pieces: concatenated 20-byte-sha1-hashes
67
+      - name:   basename of the file
68
+      - length: size of the file in bytes
69
+      - md5sum: md5sum of the file (unless disabled via include_md5)
70
+
71
+    @see:   BitTorrent Metainfo Specification.
72
+    @note:  md5 hashes in torrents are actually optional
73
+    """
74
+    assert os.path.isfile(file), "not a file"
75
+
76
+    # Total byte count.
77
+    length = 0
78
+
79
+    # Concatenated 20byte sha1-hashes of all the file's pieces.
80
+    pieces = bytearray()
81
+
82
+    md5 = hashlib.md5() if include_md5 else None
83
+
84
+    printv("Hashing file... ", end="")
85
+
86
+    with open(file, "rb") as fh:
87
+        while True:
88
+            piece_data = fh.read(piece_length)
89
+
90
+            _len = len(piece_data)
91
+            if _len == 0:
92
+                break
93
+
94
+            if include_md5:
95
+                md5.update(piece_data)
96
+
97
+            length += _len
98
+
99
+            pieces += sha1_20(piece_data)
100
+
101
+    printv("done")
102
+
103
+    assert length > 0, "empty file"
104
+
105
+    info =  {
106
+            'pieces': pieces,
107
+            'name':   os.path.basename(file),
108
+            'length': length,
109
+            
110
+            }
111
+
112
+    if include_md5:
113
+        info['md5sum'] = md5.hexdigest()
114
+
115
+    return info
116
+
117
+def create_multi_file_info(directory,
118
+                           files,
119
+                           piece_length,
120
+                           include_md5=True):
121
+    """
122
+    Return dictionary with the following keys:
123
+      - pieces: concatenated 20-byte-sha1-hashes
124
+      - name:   basename of the directory (default name of all torrents)
125
+      - files:  a list of dictionaries with the following keys:
126
+        - length: size of the file in bytes
127
+        - md5sum: md5 sum of the file (unless disabled via include_md5)
128
+        - path:   path to the file, relative to the initial directory,
129
+                  given as list.
130
+                  Examples:
131
+                  -> ["dir1", "dir2", "file.ext"]
132
+                  -> ["just_in_the_initial_directory_itself.ext"]
133
+
134
+    @see:   BitTorrent Metainfo Specification.
135
+    @note:  md5 hashes in torrents are actually optional
136
+    """
137
+    assert os.path.isdir(directory), "not a directory"
138
+
139
+    # Concatenated 20byte sha1-hashes of all the torrent's pieces.
140
+    info_pieces = bytearray()
141
+
142
+    #
143
+    info_files = []
144
+
145
+    # This bytearray will be used for the calculation of info_pieces.
146
+    # At some point, every file's data will be written into data. Consecutive
147
+    # files will be written into data as a continuous stream, as required
148
+    # by info_pieces' BitTorrent specification.
149
+    data = bytearray()
150
+
151
+    for file in files:
152
+        path = os.path.join(directory, file)
153
+
154
+        # File's byte count.
155
+        length = 0
156
+
157
+        # File's md5sum.
158
+        md5 = hashlib.md5() if include_md5 else None
159
+
160
+        printv("Processing file '%s'... " % os.path.relpath(path, directory),
161
+               end="")
162
+
163
+        with open(path, "rb") as fh:
164
+            while True:
165
+                filedata = fh.read(piece_length)
166
+
167
+                if len(filedata) == 0:
168
+                    break
169
+
170
+                length += len(filedata)
171
+
172
+                data += filedata
173
+
174
+                if len(data) >= piece_length:
175
+                    info_pieces  +=  sha1_20(data[:piece_length])
176
+                    data          =  data[piece_length:]
177
+
178
+                if include_md5:
179
+                    md5.update(filedata)
180
+
181
+        printv("done")
182
+
183
+        # Build the current file's dictionary.
184
+        fdict = {
185
+                'length': length,
186
+                'path':   split_path(file)
187
+                }
188
+
189
+        if include_md5:
190
+            fdict['md5sum'] = md5.hexdigest()
191
+
192
+        info_files.append(fdict)
193
+
194
+    # Don't forget to hash the last piece.
195
+    # (Probably the piece that has not reached the regular piece size.)
196
+    if len(data) > 0:
197
+        info_pieces += sha1_20(data)
198
+
199
+    # Build the final dictionary.
200
+    info = {
201
+           'pieces': info_pieces,
202
+           'name':   os.path.basename(directory.strip("/\\")),
203
+           'files':  info_files
204
+           }
205
+
206
+    return info
207
+
208
+def get_files_in_directory(directory,
209
+                           excluded_paths=set(),
210
+                           relative_to=None,
211
+                           excluded_regexps=set()):
212
+    """
213
+    Return a list containing the paths to all files in the given directory.
214
+
215
+    Paths in excluded_paths are skipped. These should be os.path.normcase()-d.
216
+    Of course, the initial directory cannot be excluded.
217
+    Paths matching any of the regular expressions in excluded_regexps are
218
+    skipped, too. The regexps must be compiled by the caller.
219
+    In both cases, absolute paths are used for matching.
220
+
221
+    The paths may be returned relative to a specific directory. By default,
222
+    this is the initial directory itself.
223
+
224
+    Please note: Only paths to files are returned!
225
+    
226
+    @param excluded_regexps: A set or frozenset of compiled regular expressions.
227
+    """
228
+    # Argument validation:
229
+    if not isinstance(directory, str):
230
+        raise TypeError("directory must be instance of: str")
231
+
232
+    if not isinstance(excluded_paths, (set, frozenset)):
233
+        raise TypeError("excluded_paths must be instance of: set or frozenset")
234
+
235
+    if relative_to is not None:
236
+        if not isinstance(relative_to, str):
237
+            raise TypeError("relative_to must be instance of: str")
238
+
239
+        if not os.path.isdir(relative_to):
240
+            raise ValueError("relative_to: '%s' is not a valid directory" %
241
+                             (relative_to))
242
+
243
+    if not isinstance(excluded_regexps, (set, frozenset)):
244
+        raise TypeError("excluded_regexps must be instance of: set or frozenset")
245
+
246
+    # Helper function:
247
+    def _get_files_in_directory(directory,
248
+                                files,
249
+                                excluded_paths=set(),
250
+                                relative_to=None,
251
+                                excluded_regexps=set(),
252
+                                processed_paths=set()):
253
+        # Improve consistency across platforms.
254
+        # Note:
255
+        listdir = os.listdir(directory)
256
+        listdir.sort(key=str.lower)
257
+
258
+        processed_paths.add(os.path.normcase(os.path.realpath(directory)))
259
+
260
+        for node in listdir:
261
+            path = os.path.join(directory, node)
262
+
263
+            if os.path.normcase(path) in excluded_paths:
264
+                printv("Skipping '%s' due to explicit exclusion." %
265
+                       os.path.relpath(path, relative_to))
266
+                continue
267
+
268
+            regexp_match = False
269
+            for regexp in excluded_regexps:
270
+                if regexp.search(path):
271
+                    printv("Skipping '%s' due to pattern exclusion." %
272
+                           os.path.relpath(path, relative_to))
273
+                    regexp_match = True
274
+                    break
275
+            if regexp_match:
276
+                continue
277
+
278
+            if os.path.normcase(os.path.realpath(path)) in processed_paths:
279
+                print("Warning: skipping symlink '%s', because it's target "
280
+                      "has already been processed." % path, file=sys.stderr)
281
+                continue
282
+            processed_paths.add(os.path.normcase(os.path.realpath(path)))
283
+
284
+            if os.path.isfile(path):
285
+                if relative_to:
286
+                    path = os.path.relpath(path, relative_to)
287
+                files.append(path)
288
+            elif os.path.isdir(path):
289
+                _get_files_in_directory(path,
290
+                                        files,
291
+                                        excluded_paths=excluded_paths,
292
+                                        relative_to=relative_to,
293
+                                        excluded_regexps=excluded_regexps,
294
+                                        processed_paths=processed_paths)
295
+            else:
296
+                assert False, "not a valid node: '%s'" % node
297
+
298
+        return files
299
+
300
+    # Final preparations:
301
+    directory = os.path.abspath(directory)
302
+
303
+    if not relative_to:
304
+        relative_to = directory
305
+
306
+    # Now do the main work.
307
+    files = _get_files_in_directory(directory,
308
+                                    list(),
309
+                                    excluded_paths=excluded_paths,
310
+                                    relative_to=relative_to,
311
+                                    excluded_regexps=excluded_regexps)
312
+
313
+    return files
314
+
315
+def split_path(path):
316
+    """
317
+    Return a list containing all of a path's components.
318
+
319
+    Paths containing relative components get resolved first.
320
+
321
+    >>> split_path("this/./is/a/very/../fucked\\path/file.ext")
322
+    ['this', 'is', 'a', 'fucked', 'path', 'file.ext']
323
+    """
324
+    if not isinstance(path, str):
325
+        raise TypeError("path must be instance of: str")
326
+
327
+    parts = []
328
+
329
+    path = os.path.normpath(path)
330
+
331
+    head = path
332
+
333
+    while len(head) != 0:
334
+        (head, tail) = os.path.split(head)
335
+        parts.insert(0, tail)
336
+
337
+    return parts
338
+
339
+def remove_duplicates(old_list):
340
+    """
341
+    Remove any duplicates in old_list, preserving the order of its
342
+    elements.
343
+
344
+    Thus, for all duplicate entries only the first entry is kept in
345
+    the list.
346
+    """
347
+    new_list = list()
348
+    added_items = set()
349
+
350
+    for item in old_list:
351
+        if item in added_items:
352
+            continue
353
+
354
+        added_items.add(item)
355
+        new_list.append(item)
356
+
357
+    return new_list
358
+
359
+def replace_in_list(old_list, replacements):
360
+    """
361
+    Replace specific items in a list.
362
+
363
+    Note that one element may be replaced by multiple new elements.
364
+    However, this also makes it impossible to replace an item with a
365
+    list.
366
+
367
+    Example given:
368
+    >>> replace_in_list(['dont',
369
+                         'replace',
370