Apply a patch from Gisle Vanem to make tor-gencert build under MSVC
[tor/neena.git] / doc / HACKING
blobbc409dc0d026bbea0049882b9e61b5e78d0aff23
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 git://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 _actively
42 developed_ series that has that bug.  (Right now, that's 0.2.1.)  If you're
43 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 9999; 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 The buildbot
94 ~~~~~~~~~~~~
96 https://buildbot.vidalia-project.net/one_line_per_build
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   make clean
122   make CFLAGS='-g -fprofile-arcs -ftest-coverage'
123   ./src/test/test
124   cd src/common; gcov *.[ch]
125   cd ../or; gcov *.[ch]
126 -----
128 Then, look at the .gcov files.  '-' before a line means that the
129 compiler generated  no code for that line.  '######' means that the
130 line was never reached.  Lines with numbers were called that number
131 of times.
133 Profiling Tor with oprofile
134 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
136 The oprofile tool runs (on Linux only!) to tell you what functions Tor is
137 spending its CPU time in, so we can identify berformance pottlenecks.
139 Here are some basic instructions
141  - Build tor with debugging symbols (you probably already have, unless
142    you messed with CFLAGS during the build process).
143  - Build all the libraries you care about with debugging symbols
144    (probably you only care about libssl, maybe zlib and Libevent).
145  - Copy this tor to a new directory
146  - Copy all the libraries it uses to that dir too (ldd ./tor will
147    tell you)
148  - Set LD_LIBRARY_PATH to include that dir.  ldd ./tor should now
149    show you it's using the libs in that dir
150  - Run that tor
151  - Reset oprofiles counters/start it
152    * "opcontrol --reset; opcontrol --start", if Nick remembers right.
153  - After a while, have it dump the stats on tor and all the libs
154    in that dir you created.
155    * "opcontrol --dump;"
156    * "opreport -l that_dir/*"
157  - Profit
160 Coding conventions
161 ------------------
163 Patch checklist
164 ~~~~~~~~~~~~~~~
166 If possible, send your patch as one of these (in descending order of
167 preference)
169    - A git branch we can pull from
170    - Patches generated by git format-patch
171    - A unified diff
173 Did you remember...
175    - To build your code while configured with --enable-gcc-warnings?
176    - To run "make check-spaces" on your code?
177    - To write unit tests, as possible?
178    - To base your code on the appropriate branch?
179    - To include a file in the "changes" directory as appropriate?
181 Whitespace and C conformance
182 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
184 Invoke "make check-spaces" from time to time, so it can tell you about
185 deviations from our C whitespace style.  Generally, we use:
187     - Unix-style line endings
188     - K&R-style indentation
189     - No space before newlines
190     - A blank line at the end of each file
191     - Never more than one blank line in a row
192     - Always spaces, never tabs
193     - No more than 79-columns per line.
194     - Two spaces per indent.
195     - A space between control keywords and their corresponding paren
196       "if (x)", "while (x)", and "switch (x)", never "if(x)", "while(x)", or
197       "switch(x)".
198     - A space between anything and an open brace.
199     - No space between a function name and an opening paren. "puts(x)", not
200       "puts (x)".
201     - Function declarations at the start of the line.
203 We try hard to build without warnings everywhere.  In particular, if you're
204 using gcc, you should invoke the configure script with the option
205 "--enable-gcc-warnings".  This will give a bunch of extra warning flags to
206 the compiler, and help us find divergences from our preferred C style.
208 Getting emacs to edit Tor source properly
209 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
211 Nick likes to put the following snippet in his .emacs file:
213 -----
214     (add-hook 'c-mode-hook
215           (lambda ()
216             (font-lock-mode 1)
217             (set-variable 'show-trailing-whitespace t)
219             (let ((fname (expand-file-name (buffer-file-name))))
220               (cond
221                ((string-match "^/home/nickm/src/libevent" fname)
222                 (set-variable 'indent-tabs-mode t)
223                 (set-variable 'c-basic-offset 4)
224                 (set-variable 'tab-width 4))
225                ((string-match "^/home/nickm/src/tor" fname)
226                 (set-variable 'indent-tabs-mode nil)
227                 (set-variable 'c-basic-offset 2))
228                ((string-match "^/home/nickm/src/openssl" fname)
229                 (set-variable 'indent-tabs-mode t)
230                 (set-variable 'c-basic-offset 8)
231                 (set-variable 'tab-width 8))
232             ))))
233 -----
235 You'll note that it defaults to showing all trailing whitespace.  The "cond"
236 test detects whether the file is one of a few C free software projects that I
237 often edit, and sets up the indentation level and tab preferences to match
238 what they want.
240 If you want to try this out, you'll need to change the filename regex
241 patterns to match where you keep your Tor files.
243 If you use emacs for editing Tor and nothing else, you could always just say:
245 -----
246    (add-hook 'c-mode-hook
247           (lambda ()
248             (font-lock-mode 1)
249             (set-variable 'show-trailing-whitespace t)
250             (set-variable 'indent-tabs-mode nil)
251             (set-variable 'c-basic-offset 2)))
252 -----
254 There is probably a better way to do this.  No, we are probably not going
255 to clutter the files with emacs stuff.
258 Functions to use
259 ~~~~~~~~~~~~~~~~
261 We have some wrapper functions like tor_malloc, tor_free, tor_strdup, and
262 tor_gettimeofday; use them instead of their generic equivalents.  (They
263 always succeed or exit.)
265 You can get a full list of the compatibility functions that Tor provides by
266 looking through src/common/util.h and src/common/compat.h.  You can see the
267 available containers in src/common/containers.h.  You should probably
268 familiarize yourself with these modules before you write too much code, or
269 else you'll wind up reinventing the wheel.
271 Use 'INLINE' instead of 'inline', so that we work properly on Windows.
273 Calling and naming conventions
274 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
276 Whenever possible, functions should return -1 on error and 0 on success.
278 For multi-word identifiers, use lowercase words combined with
279 underscores. (e.g., "multi_word_identifier").  Use ALL_CAPS for macros and
280 constants.
282 Typenames should end with "_t".
284 Function names should be prefixed with a module name or object name.  (In
285 general, code to manipulate an object should be a module with the same name
286 as the object, so it's hard to tell which convention is used.)
288 Functions that do things should have imperative-verb names
289 (e.g. buffer_clear, buffer_resize); functions that return booleans should
290 have predicate names (e.g. buffer_is_empty, buffer_needs_resizing).
292 If you find that you have four or more possible return code values, it's
293 probably time to create an enum.  If you find that you are passing three or
294 more flags to a function, it's probably time to create a flags argument that
295 takes a bitfield.
297 What To Optimize
298 ~~~~~~~~~~~~~~~~
300 Don't optimize anything if it's not in the critical path.  Right now, the
301 critical path seems to be AES, logging, and the network itself.  Feel free to
302 do your own profiling to determine otherwise.
304 Log conventions
305 ~~~~~~~~~~~~~~~
307 https://wiki.torproject.org/noreply/TheOnionRouter/TorFAQ#LogLevels
309 No error or warning messages should be expected during normal OR or OP
310 operation.
312 If a library function is currently called such that failure always means ERR,
313 then the library function should log WARN and let the caller log ERR.
315 Every message of severity INFO or higher should either (A) be intelligible
316 to end-users who don't know the Tor source; or (B) somehow inform the
317 end-users that they aren't expected to understand the message (perhaps
318 with a string like "internal error"). Option (A) is to be preferred to
319 option (B).
321 Doxygen
322 ~~~~~~~~
324 We use the 'doxygen' utility to generate documentation from our
325 source code. Here's how to use it:
327   1. Begin every file that should be documented with
328          /**
329           * \file filename.c
330           * \brief Short description of the file.
331           **/
333      (Doxygen will recognize any comment beginning with /** as special.)
335   2. Before any function, structure, #define, or variable you want to
336      document, add a comment of the form:
338         /** Describe the function's actions in imperative sentences.
339          *
340          * Use blank lines for paragraph breaks
341          *   - and
342          *   - hyphens
343          *   - for
344          *   - lists.
345          *
346          * Write <b>argument_names</b> in boldface.
347          *
348          * \code
349          *     place_example_code();
350          *     between_code_and_endcode_commands();
351          * \endcode
352          */
354   3. Make sure to escape the characters "<", ">", "\", "%" and "#" as "\<",
355      "\>", "\\", "\%", and "\#".
357   4. To document structure members, you can use two forms:
359        struct foo {
360          /** You can put the comment before an element; */
361          int a;
362          int b; /**< Or use the less-than symbol to put the comment
363                  * after the element. */
364        };
366   5. To generate documentation from the Tor source code, type:
368      $ doxygen -g
370      To generate a file called 'Doxyfile'.  Edit that file and run
371      'doxygen' to generate the API documentation.
373   6. See the Doxygen manual for more information; this summary just
374      scratches the surface.
376 Doxygen comment conventions
377 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
379 Say what functions do as a series of one or more imperative sentences, as
380 though you were telling somebody how to be the function.  In other words, DO
381 NOT say:
383      /** The strtol function parses a number.
384       *
385       * nptr -- the string to parse.  It can include whitespace.
386       * endptr -- a string pointer to hold the first thing that is not part
387       *    of the number, if present.
388       * base -- the numeric base.
389       * returns: the resulting number.
390       */
391      long strtol(const char *nptr, char **nptr, int base);
393 Instead, please DO say:
395      /** Parse a number in radix <b>base</b> from the string <b>nptr</b>,
396       * and return the result.  Skip all leading whitespace.  If
397       * <b>endptr</b> is not NULL, set *<b>endptr</b> to the first character
398       * after the number parsed.
399       **/
400      long strtol(const char *nptr, char **nptr, int base);
402 Doxygen comments are the contract in our abstraction-by-contract world: if
403 the functions that call your function rely on it doing something, then your
404 function should mention that it does that something in the documentation.  If
405 you rely on a function doing something beyond what is in its documentation,
406 then you should watch out, or it might do something else later.
408 Putting out a new release
409 -------------------------
411 Here are the steps Roger takes when putting out a new Tor release:
413 1) Use it for a while, as a client, as a relay, as a hidden service,
414 and as a directory authority. See if it has any obvious bugs, and
415 resolve those.
417 1.5) As applicable, merge the maint-X branch into the release-X branch.
419 2) Gather the changes/* files into a changelog entry, rewriting many
420 of them and reordering to focus on what users and funders would find
421 interesting and understandable.
423    2.1) Make sure that everything that wants a bug number has one.
424    2.2) Concatenate them.
425    2.3) Sort them by section.  Within each section, try to make the
426       first entry or two and the last entry most interesting: they're
427       the ones that skimmers tend to read.
429    2.4) Clean them up:
431    Standard idioms:
432      "Fixes bug 9999; bugfix on 0.3.3.3-alpha."
434    One period after a space.
436    Make stuff very terse
438    Make sure each section name ends with a colon
440    Describe the user-visible problem right away
442    Mention relevant config options by name.  If they're rare or unusual,
443    remind people what they're for
445    Avoid starting lines with open-paren
447    Present and imperative tense: not past.
449    Try not to let any given section be longer than about a page. Break up
450    long sections into subsections by some sort of common subtopic. This
451    guideline is especially important when organizing Release Notes for
452    new stable releases.
454    If a given changes stanza showed up in a different release (e.g.
455    maint-0.2.1), be sure to make the stanzas identical (so people can
456    distinguish if these are the same change).
458    2.5) Merge them in.
460    2.6) Clean everything one last time.
462    2.7) Run it through fmt to make it pretty.
464 3) Compose a short release blurb to highlight the user-facing
465 changes. Insert said release blurb into the ChangeLog stanza. If it's
466 a stable release, add it to the ReleaseNotes file too. If we're adding
467 to a release-0.2.x branch, manually commit the changelogs to the later
468 git branches too.
470 4) Bump the version number in configure.in and rebuild.
472 5) Make dist, put the tarball up somewhere, and tell #tor about it. Wait
473 a while to see if anybody has problems building it. Try to get Sebastian
474 or somebody to try building it on Windows.
476 6) Get at least two of weasel/arma/sebastian to put the new version number
477 in their approved versions list.
479 7) Sign the tarball, then sign and push the git tag:
480   gpg -ba <the_tarball>
481   git tag -u <keyid> tor-0.2.x.y-status
482   git push origin tag tor-0.2.x.y-status
484 8) scp the tarball and its sig to the website in the dist/ directory
485 (i.e. /srv/www-master.torproject.org/htdocs/dist/ on vescum). Edit
486 include/versions.wmi to note the new version. From your website checkout,
487 run ./publish to build and publish the website.
489 Try not to delay too much between scp'ing the tarball and running
490 ./publish -- the website has multiple A records and your scp only sent
491 it to one of them.
493 9) Email Erinn and weasel (cc'ing tor-assistants) that a new tarball
494 is up. This step should probably change to mailing more packagers.
496 10) Add the version number to Trac.  To do this, go to Trac, log in,
497 select "Admin" near the top of the screen, then select "Versions" from
498 the menu on the left.  At the right, there will be an "Add version"
499 box.  By convention, we enter the version in the form "Tor:
500 0.2.2.23-alpha" (or whatever the version is), and we select the date as
501 the date in the ChangeLog.
503 11) Forward-port the ChangeLog.
505 12) Update the topic in #tor to reflect the new version.
507 12) Wait up to a day or two (for a development release), or until most
508 packages are up (for a stable release), and mail the release blurb and
509 changelog to tor-talk or tor-announce.
511   (We might be moving to faster announcements, but don't announce until
512   the website is at least updated.)