Merge branch 'maint-0.2.4' into maint-0.2.5
[tor.git] / doc / HACKING
blobc69b2a6fee9e3248459a66f026958fe5d03b13b8
1 Hacking Tor: An Incomplete Guide
2 ================================
4 Getting started
5 ---------------
7 For full information on how Tor is supposed to work, look at the files in
8 https://gitweb.torproject.org/torspec.git/tree
10 For an explanation of how to change Tor's design to work differently, look at
11 https://gitweb.torproject.org/torspec.git/blob_plain/HEAD:/proposals/001-process.txt
13 For the latest version of the code, get a copy of git, and
15    git clone https://git.torproject.org/git/tor
17 We talk about Tor on the tor-talk mailing list.  Design proposals and
18 discussion belong on the tor-dev mailing list.  We hang around on
19 irc.oftc.net, with general discussion happening on #tor and development
20 happening on #tor-dev.
22 How we use Git branches
23 -----------------------
25 Each main development series (like 0.2.1, 0.2.2, etc) has its main work
26 applied to a single branch.  At most one series can be the development series
27 at a time; all other series are maintenance series that get bug-fixes only.
28 The development series is built in a git branch called "master"; the
29 maintenance series are built in branches called "maint-0.2.0", "maint-0.2.1",
30 and so on.  We regularly merge the active maint branches forward.
32 For all series except the development series, we also have a "release" branch
33 (as in "release-0.2.1").  The release series is based on the corresponding
34 maintenance series, except that it deliberately lags the maint series for
35 most of its patches, so that bugfix patches are not typically included in a
36 maintenance release until they've been tested for a while in a development
37 release.  Occasionally, we'll merge an urgent bugfix into the release branch
38 before it gets merged into maint, but that's rare.
40 If you're working on a bugfix for a bug that occurs in a particular version,
41 base your bugfix branch on the "maint" branch for the first supported series
42 that has that bug.  (As of June 2013, we're supporting 0.2.3 and later.) If
43 you're working on a new feature, base it on the master branch.
46 How we log changes
47 ------------------
49 When you do a commit that needs a ChangeLog entry, add a new file to
50 the "changes" toplevel subdirectory.  It should have the format of a
51 one-entry changelog section from the current ChangeLog file, as in
53   o Major bugfixes:
54     - Fix a potential buffer overflow. Fixes bug 99999; bugfix on
55       0.3.1.4-beta.
57 To write a changes file, first categorize the change.  Some common categories
58 are: Minor bugfixes, Major bugfixes, Minor features, Major features, Code
59 simplifications and refactoring.  Then say what the change does.  If
60 it's a bugfix, mention what bug it fixes and when the bug was
61 introduced.  To find out which Git tag the change was introduced in,
62 you can use "git describe --contains <sha1 of commit>".
64 If at all possible, try to create this file in the same commit where
65 you are making the change.  Please give it a distinctive name that no
66 other branch will use for the lifetime of your change.
68 When we go to make a release, we will concatenate all the entries
69 in changes to make a draft changelog, and clear the directory. We'll
70 then edit the draft changelog into a nice readable format.
72 What needs a changes file?::
73    A not-exhaustive list: Anything that might change user-visible
74    behavior. Anything that changes internals, documentation, or the build
75    system enough that somebody could notice.  Big or interesting code
76    rewrites.  Anything about which somebody might plausibly wonder "when
77    did that happen, and/or why did we do that" 6 months down the line.
79 Why use changes files instead of Git commit messages?::
80    Git commit messages are written for developers, not users, and they
81    are nigh-impossible to revise after the fact.
83 Why use changes files instead of entries in the ChangeLog?::
84    Having every single commit touch the ChangeLog file tended to create
85    zillions of merge conflicts.
87 Useful tools
88 ------------
90 These aren't strictly necessary for hacking on Tor, but they can help track
91 down bugs.
93 Jenkins
94 ~~~~~~~
96 https://jenkins.torproject.org
98 Dmalloc
99 ~~~~~~~
101 The dmalloc library will keep track of memory allocation, so you can find out
102 if we're leaking memory, doing any double-frees, or so on.
104   dmalloc -l ~/dmalloc.log
105   (run the commands it tells you)
106   ./configure --with-dmalloc
108 Valgrind
109 ~~~~~~~~
111 valgrind --leak-check=yes --error-limit=no --show-reachable=yes src/or/tor
113 (Note that if you get a zillion openssl warnings, you will also need to
114 pass --undef-value-errors=no to valgrind, or rebuild your openssl
115 with -DPURIFY.)
117 Running gcov for unit test coverage
118 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
120 -----
121    ./configure --enable-coverage
122    make
123    make check
124    mkdir coverage-output
125    ./scripts/test/coverage coverage-output
126 -----
128 (On OSX, you'll need to start with "--enable-coverage CC=clang".)
130 Then, look at the .gcov files in coverage-output.  '-' before a line means
131 that the compiler generated no code for that line.  '######' means that the
132 line was never reached.  Lines with numbers were called that number of times.
134 If that doesn't work:
135    * Try configuring Tor with --disable-gcc-hardening
136    * You might need to run 'make clean' after you run './configure'.
138 If you make changes to Tor and want to get another set of coverage results,
139 you can run "make reset-gcov" to clear the intermediary gcov output.
141 If you have two different "coverage-output" directories, and you want to see
142 a meaningful diff between them, you can run:
144 -----
145    ./scripts/test/cov-diff coverage-output1 coverage-output2 | less
146 -----
148 In this diff, any lines that were visited at least once will have coverage
149 "1".  This lets you inspect what you (probably) really want to know: which
150 untested lines were changed?  Are there any new untested lines?
152 Running integration tests
153 ~~~~~~~~~~~~~~~~~~~~~~~~~
155 We have the beginnings of a set of scripts to run integration tests using
156 Chutney. To try them, set CHUTNEY_PATH to your chutney source directory, and
157 run "make test-network".
159 Profiling Tor with oprofile
160 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
162 The oprofile tool runs (on Linux only!) to tell you what functions Tor is
163 spending its CPU time in, so we can identify berformance pottlenecks.
165 Here are some basic instructions
167  - Build tor with debugging symbols (you probably already have, unless
168    you messed with CFLAGS during the build process).
169  - Build all the libraries you care about with debugging symbols
170    (probably you only care about libssl, maybe zlib and Libevent).
171  - Copy this tor to a new directory
172  - Copy all the libraries it uses to that dir too (ldd ./tor will
173    tell you)
174  - Set LD_LIBRARY_PATH to include that dir.  ldd ./tor should now
175    show you it's using the libs in that dir
176  - Run that tor
177  - Reset oprofiles counters/start it
178    * "opcontrol --reset; opcontrol --start", if Nick remembers right.
179  - After a while, have it dump the stats on tor and all the libs
180    in that dir you created.
181    * "opcontrol --dump;"
182    * "opreport -l that_dir/*"
183  - Profit
186 Coding conventions
187 ------------------
189 Patch checklist
190 ~~~~~~~~~~~~~~~
192 If possible, send your patch as one of these (in descending order of
193 preference)
195    - A git branch we can pull from
196    - Patches generated by git format-patch
197    - A unified diff
199 Did you remember...
201    - To build your code while configured with --enable-gcc-warnings?
202    - To run "make check-spaces" on your code?
203    - To run "make check-docs" to see whether all new options are on
204      the manpage?
205    - To write unit tests, as possible?
206    - To base your code on the appropriate branch?
207    - To include a file in the "changes" directory as appropriate?
209 Whitespace and C conformance
210 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
212 Invoke "make check-spaces" from time to time, so it can tell you about
213 deviations from our C whitespace style.  Generally, we use:
215     - Unix-style line endings
216     - K&R-style indentation
217     - No space before newlines
218     - A blank line at the end of each file
219     - Never more than one blank line in a row
220     - Always spaces, never tabs
221     - No more than 79-columns per line.
222     - Two spaces per indent.
223     - A space between control keywords and their corresponding paren
224       "if (x)", "while (x)", and "switch (x)", never "if(x)", "while(x)", or
225       "switch(x)".
226     - A space between anything and an open brace.
227     - No space between a function name and an opening paren. "puts(x)", not
228       "puts (x)".
229     - Function declarations at the start of the line.
231 We try hard to build without warnings everywhere.  In particular, if you're
232 using gcc, you should invoke the configure script with the option
233 "--enable-gcc-warnings".  This will give a bunch of extra warning flags to
234 the compiler, and help us find divergences from our preferred C style.
236 Getting emacs to edit Tor source properly
237 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
239 Nick likes to put the following snippet in his .emacs file:
241 -----
242     (add-hook 'c-mode-hook
243           (lambda ()
244             (font-lock-mode 1)
245             (set-variable 'show-trailing-whitespace t)
247             (let ((fname (expand-file-name (buffer-file-name))))
248               (cond
249                ((string-match "^/home/nickm/src/libevent" fname)
250                 (set-variable 'indent-tabs-mode t)
251                 (set-variable 'c-basic-offset 4)
252                 (set-variable 'tab-width 4))
253                ((string-match "^/home/nickm/src/tor" fname)
254                 (set-variable 'indent-tabs-mode nil)
255                 (set-variable 'c-basic-offset 2))
256                ((string-match "^/home/nickm/src/openssl" fname)
257                 (set-variable 'indent-tabs-mode t)
258                 (set-variable 'c-basic-offset 8)
259                 (set-variable 'tab-width 8))
260             ))))
261 -----
263 You'll note that it defaults to showing all trailing whitespace.  The "cond"
264 test detects whether the file is one of a few C free software projects that I
265 often edit, and sets up the indentation level and tab preferences to match
266 what they want.
268 If you want to try this out, you'll need to change the filename regex
269 patterns to match where you keep your Tor files.
271 If you use emacs for editing Tor and nothing else, you could always just say:
273 -----
274    (add-hook 'c-mode-hook
275           (lambda ()
276             (font-lock-mode 1)
277             (set-variable 'show-trailing-whitespace t)
278             (set-variable 'indent-tabs-mode nil)
279             (set-variable 'c-basic-offset 2)))
280 -----
282 There is probably a better way to do this.  No, we are probably not going
283 to clutter the files with emacs stuff.
286 Functions to use
287 ~~~~~~~~~~~~~~~~
289 We have some wrapper functions like tor_malloc, tor_free, tor_strdup, and
290 tor_gettimeofday; use them instead of their generic equivalents.  (They
291 always succeed or exit.)
293 You can get a full list of the compatibility functions that Tor provides by
294 looking through src/common/util.h and src/common/compat.h.  You can see the
295 available containers in src/common/containers.h.  You should probably
296 familiarize yourself with these modules before you write too much code, or
297 else you'll wind up reinventing the wheel.
299 Use 'INLINE' instead of 'inline', so that we work properly on Windows.
301 Calling and naming conventions
302 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
304 Whenever possible, functions should return -1 on error and 0 on success.
306 For multi-word identifiers, use lowercase words combined with
307 underscores. (e.g., "multi_word_identifier").  Use ALL_CAPS for macros and
308 constants.
310 Typenames should end with "_t".
312 Function names should be prefixed with a module name or object name.  (In
313 general, code to manipulate an object should be a module with the same name
314 as the object, so it's hard to tell which convention is used.)
316 Functions that do things should have imperative-verb names
317 (e.g. buffer_clear, buffer_resize); functions that return booleans should
318 have predicate names (e.g. buffer_is_empty, buffer_needs_resizing).
320 If you find that you have four or more possible return code values, it's
321 probably time to create an enum.  If you find that you are passing three or
322 more flags to a function, it's probably time to create a flags argument that
323 takes a bitfield.
325 What To Optimize
326 ~~~~~~~~~~~~~~~~
328 Don't optimize anything if it's not in the critical path.  Right now, the
329 critical path seems to be AES, logging, and the network itself.  Feel free to
330 do your own profiling to determine otherwise.
332 Log conventions
333 ~~~~~~~~~~~~~~~
335 https://trac.torproject.org/projects/tor/wiki/doc/TorFAQ#loglevel
337 No error or warning messages should be expected during normal OR or OP
338 operation.
340 If a library function is currently called such that failure always means ERR,
341 then the library function should log WARN and let the caller log ERR.
343 Every message of severity INFO or higher should either (A) be intelligible
344 to end-users who don't know the Tor source; or (B) somehow inform the
345 end-users that they aren't expected to understand the message (perhaps
346 with a string like "internal error"). Option (A) is to be preferred to
347 option (B).
349 Doxygen
350 ~~~~~~~~
352 We use the 'doxygen' utility to generate documentation from our
353 source code. Here's how to use it:
355   1. Begin every file that should be documented with
356          /**
357           * \file filename.c
358           * \brief Short description of the file.
359           **/
361      (Doxygen will recognize any comment beginning with /** as special.)
363   2. Before any function, structure, #define, or variable you want to
364      document, add a comment of the form:
366         /** Describe the function's actions in imperative sentences.
367          *
368          * Use blank lines for paragraph breaks
369          *   - and
370          *   - hyphens
371          *   - for
372          *   - lists.
373          *
374          * Write <b>argument_names</b> in boldface.
375          *
376          * \code
377          *     place_example_code();
378          *     between_code_and_endcode_commands();
379          * \endcode
380          */
382   3. Make sure to escape the characters "<", ">", "\", "%" and "#" as "\<",
383      "\>", "\\", "\%", and "\#".
385   4. To document structure members, you can use two forms:
387        struct foo {
388          /** You can put the comment before an element; */
389          int a;
390          int b; /**< Or use the less-than symbol to put the comment
391                  * after the element. */
392        };
394   5. To generate documentation from the Tor source code, type:
396      $ doxygen -g
398      To generate a file called 'Doxyfile'.  Edit that file and run
399      'doxygen' to generate the API documentation.
401   6. See the Doxygen manual for more information; this summary just
402      scratches the surface.
404 Doxygen comment conventions
405 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
407 Say what functions do as a series of one or more imperative sentences, as
408 though you were telling somebody how to be the function.  In other words, DO
409 NOT say:
411      /** The strtol function parses a number.
412       *
413       * nptr -- the string to parse.  It can include whitespace.
414       * endptr -- a string pointer to hold the first thing that is not part
415       *    of the number, if present.
416       * base -- the numeric base.
417       * returns: the resulting number.
418       */
419      long strtol(const char *nptr, char **nptr, int base);
421 Instead, please DO say:
423      /** Parse a number in radix <b>base</b> from the string <b>nptr</b>,
424       * and return the result.  Skip all leading whitespace.  If
425       * <b>endptr</b> is not NULL, set *<b>endptr</b> to the first character
426       * after the number parsed.
427       **/
428      long strtol(const char *nptr, char **nptr, int base);
430 Doxygen comments are the contract in our abstraction-by-contract world: if
431 the functions that call your function rely on it doing something, then your
432 function should mention that it does that something in the documentation.  If
433 you rely on a function doing something beyond what is in its documentation,
434 then you should watch out, or it might do something else later.
436 Putting out a new release
437 -------------------------
439 Here are the steps Roger takes when putting out a new Tor release:
441 1) Use it for a while, as a client, as a relay, as a hidden service,
442 and as a directory authority. See if it has any obvious bugs, and
443 resolve those.
445 1.5) As applicable, merge the maint-X branch into the release-X branch.
447 2) Gather the changes/* files into a changelog entry, rewriting many
448 of them and reordering to focus on what users and funders would find
449 interesting and understandable.
451    2.1) Make sure that everything that wants a bug number has one.
452         Make sure that everything which is a bugfix says what version
453         it was a bugfix on.
454    2.2) Concatenate them.
455    2.3) Sort them by section. Within each section, sort by "version it's
456         a bugfix on", else by numerical ticket order.
458    2.4) Clean them up:
460    Standard idioms:
461      "Fixes bug 9999; bugfix on 0.3.3.3-alpha."
463    One period after a space.
465    Make stuff very terse
467    Make sure each section name ends with a colon
469    Describe the user-visible problem right away
471    Mention relevant config options by name.  If they're rare or unusual,
472    remind people what they're for
474    Avoid starting lines with open-paren
476    Present and imperative tense: not past.
478    'Relays', not 'servers' or 'nodes' or 'Tor relays'.
480    "Stop FOOing", not "Fix a bug where we would FOO".
482    Try not to let any given section be longer than about a page. Break up
483    long sections into subsections by some sort of common subtopic. This
484    guideline is especially important when organizing Release Notes for
485    new stable releases.
487    If a given changes stanza showed up in a different release (e.g.
488    maint-0.2.1), be sure to make the stanzas identical (so people can
489    distinguish if these are the same change).
491    2.5) Merge them in.
493    2.6) Clean everything one last time.
495    2.7) Run it through fmt to make it pretty.
497 3) Compose a short release blurb to highlight the user-facing
498 changes. Insert said release blurb into the ChangeLog stanza. If it's
499 a stable release, add it to the ReleaseNotes file too. If we're adding
500 to a release-0.2.x branch, manually commit the changelogs to the later
501 git branches too.
503 4) Bump the version number in configure.ac and rebuild.
505 5) Make dist, put the tarball up somewhere, and tell #tor about it. Wait
506 a while to see if anybody has problems building it. Try to get Sebastian
507 or somebody to try building it on Windows.
509 6) Get at least two of weasel/arma/sebastian to put the new version number
510 in their approved versions list.
512 7) Sign the tarball, then sign and push the git tag:
513   gpg -ba <the_tarball>
514   git tag -u <keyid> tor-0.2.x.y-status
515   git push origin tag tor-0.2.x.y-status
517 8) scp the tarball and its sig to the website in the dist/ directory
518 (i.e. /srv/www-master.torproject.org/htdocs/dist/ on vescum). Edit
519 "include/versions.wmi" and "Makefile" to note the new version. From your
520 website checkout, run ./publish to build and publish the website.
522 9) Email the packagers (cc'ing tor-assistants) that a new tarball is up.
524 10) Add the version number to Trac.  To do this, go to Trac, log in,
525 select "Admin" near the top of the screen, then select "Versions" from
526 the menu on the left.  At the right, there will be an "Add version"
527 box.  By convention, we enter the version in the form "Tor:
528 0.2.2.23-alpha" (or whatever the version is), and we select the date as
529 the date in the ChangeLog.
531 11) Forward-port the ChangeLog.
533 12) Wait up to a day or two (for a development release), or until most
534 packages are up (for a stable release), and mail the release blurb and
535 changelog to tor-talk or tor-announce.
537   (We might be moving to faster announcements, but don't announce until
538   the website is at least updated.)
540 13) If it's a stable release, bump the version number in the maint-x.y.z
541     branch to "newversion-dev", and do a "merge -s ours" merge to avoid
542     taking that change into master.  Do a similar 'merge -s theirs'
543     merge to get the change (and only that change) into release.  (Some
544     of the build scripts require that maint merge cleanly into release.)