more information why nat tests fail
[oweals/gnunet.git] / doc / gnunet-c-tutorial.tex
1 \documentclass[10pt]{article}
2 \usepackage[ansinew]{inputenc}
3 \usepackage{makeidx,amsmath,amssymb,exscale,multicol,epsfig,graphics,verbatim,ulem}
4 \usepackage{epsfig,geometry,url,listings, subcaption}
5 \usepackage{boxedminipage}
6 \usepackage[T1]{fontenc}%required
7 \usepackage{textcomp}
8 \geometry{headsep=3ex,hscale=0.9}
9 \usepackage{hyperref}
10 \hypersetup{pdftitle={GNUnet C Tutorial},
11   pdfsubject={GNUnet},
12   pdfauthor={Christian Grothoff <christian@grothoff.org>},
13   pdfkeywords={p2p,search,gnunet,tutorial}
14   %,pdfpagemode={FullScreen}
15   }
16
17
18 \lstset{
19 language=bash,
20 basicstyle=\ttfamily,
21 upquote=true,
22 columns=fullflexible,
23 literate={*}{{\char42}}1
24          {-}{{\char45}}1
25 }
26
27 \newcommand{\exercise}[1]{\noindent\begin{boxedminipage}{\textwidth}{\bf Exercise:} #1 \end{boxedminipage}}
28
29 \begin{document}
30
31 \begin{center}
32 \large {A Tutorial for GNUnet 0.10.x (C version)}
33
34 Christian Grothoff $\qquad$ Bart Polot $\qquad$ Matthias Wachs
35
36 \today
37 \end{center}
38 This tutorials explains how to install GNUnet on a GNU/Linux system and gives an introduction how
39 GNUnet can be used to develop a Peer-to-Peer application. Detailed installation instructions for
40 various operating systems and a detailed list of all dependencies can found on our website at
41 \url{https://gnunet.org/installation}.
42
43 \textbf{Please read this tutorial carefully since every single step is
44   important and do not hesitate to contact the GNUnet team if you have
45   any questions or problems! Check here how to contact the GNUnet
46   team: \url{https://gnunet.org/contact_information}}
47
48
49 \section{Installing GNUnet}
50 First of all you have to install a current version of GNUnet. You can download a
51 tarball of a stable version from GNU FTP mirrors or obtain the latest development
52 version from our Subversion repository.
53
54 Most of the time you should prefer to download the stable version since with the
55 latest development version things can be broken, functionality can be changed or tests
56 can fail. You should only use the development version if you know that you require a
57 certain feature or a certain issue has been fixed since the last release.
58
59 \subsection{Obtaining a stable version}
60 You can download the latest stable version of GNUnet from GNU FTP mirrors:
61 \begin{center}
62 \url{ftp://ftp.gnu.org/gnu/gnunet/gnunet-0.10.x.tar.gz}
63 \end{center}
64 You should also download the signature file and verify the integrity of the tarball.
65 \begin{center}
66 \url{ftp://ftp.gnu.org/gnu/gnunet/gnunet-0.10.x.tar.gz.sig}
67 \end{center}
68 To verify the signature you should first import the GPG key used to sign the tarball
69 \begin{lstlisting}
70 $ gpg --keyserver keys.gnupg.net --recv-keys 48426C7E
71 \end{lstlisting}
72 And use this key to verify the tarball's signature
73 \begin{lstlisting}
74 $ gpg --verify gnunet-0.10.x.tar.gz.sig gnunet-0.10.x.tar.gz
75 \end{lstlisting}
76 After successfully verifying the integrity you can extract the tarball using
77 \begin{lstlisting}
78 $ tar xvzf gnunet-0.10.x.tar.gz
79 $ mv gnunet-0.10.x gnunet # we will use the directory "gnunet" in the remainder of this document
80 $ cd gnunet
81 \end{lstlisting}
82
83 \subsection{Installing Build Tool Chain and Dependencies}
84 To successfully compile GNUnet you need the tools to build GNUnet and the required dependencies.
85 Please have a look at \url{https://gnunet.org/dependencies} for a list of required dependencies
86 and \url{https://gnunet.org/generic_installation} for specific instructions for your operating system.
87
88 Please check the notes at the end of the configure process about required dependencies.
89
90 For GNUNet bootstrapping support and the http(s) plugin you should install \texttt{libcurl}.
91 For the filesharing service you should install at least one of the datastore backends \texttt{mysql},
92 \texttt{sqlite} or \texttt{postgresql}.
93
94 \subsection{Obtaining the latest version from Subversion}
95 The latest development version can obtained from our Subversion (\textit{svn}) repository. To obtain
96 the code you need Subversion installed and checkout the repository using:
97 \lstset{language=bash}
98 \begin{lstlisting}
99 $ svn checkout https://gnunet.org/svn/gnunet
100 \end{lstlisting}
101 After cloning the repository you have to execute
102 \lstset{language=bash}
103 \begin{lstlisting}
104 $ cd gnunet
105 $ ./bootstrap
106 \end{lstlisting}
107
108 The remainder of this tutorial assumes that you have SVN HEAD checked out.
109
110 \subsection{Compiling and Installing GNUnet}
111
112 First, you need to install at least {\tt libgnupgerror} version
113 1.12\footnote{\url{ftp://ftp.gnupg.org/gcrypt/libgpg-error/libgpg-error-1.12.tar.bz2}}
114 and {\tt libgcrypt} version
115 1.6\footnote{\url{ftp://ftp.gnupg.org/gcrypt/libgcrypt/libgcrypt-1.6.0.tar.bz2}}.
116
117 \lstset{language=bash}
118 \begin{lstlisting}
119 $ wget ftp://ftp.gnupg.org/gcrypt/libgpg-error/libgpg-error-1.12.tar.bz2
120 $ tar xf libgpg-error-1.12.tar.bz2
121 $ cd libgpg-error-1.12
122 $ ./configure
123 $ sudo make install
124 $ cd ..
125 \end{lstlisting}
126
127 \lstset{language=bash}
128 \begin{lstlisting}
129 $ wget ftp://ftp.gnupg.org/gcrypt/libgcrypt/libgcrypt-1.6.0.tar.bz2
130 $ tar xf libgcrypt-1.6.0.tar.bz2
131 $ cd libgcrypt-1.6.0
132 $ ./configure
133 $ sudo make install
134 $ cd ..
135 \end{lstlisting}
136
137 \label{sub:install}
138 Assuming all dependencies are installed, the following commands will
139 compile and install GNUnet in your home directory. You can specify the
140 directory where GNUnet will be installed by changing the
141 \lstinline|--prefix| value when calling \lstinline|./configure|.  If
142 you do not specifiy a prefix, GNUnet is installed in the directory
143 \lstinline|/usr/local|. When developing new applications you may want
144 to enable verbose logging by adding
145 \lstinline|--enable-logging=verbose|:
146
147 \lstset{language=bash}
148 \begin{lstlisting}
149 $ ./configure --prefix=$HOME --enable-logging
150 $ make
151 $ make install
152 \end{lstlisting}
153
154 After installing GNUnet you have to set the \lstinline|GNUNET_PREFIX|
155 environmental variable used by GNUnet to detect it's installation
156 directory and add your GNUnet installation to your path environmental
157 variable.  This configuration is only valid for the current shell
158 session, so you should add \lstinline|export GNUNET_PREFIX=$HOME| to
159 your \lstinline|.bash_rc| or \lstinline|.profile| to be sure the
160 environment variable is always set. In addition you have to create the
161 \lstinline|.gnunet| directory in your home directory where GNUnet
162 stores it's data and an empty GNUnet configuration file:
163
164 \lstset{language=bash}
165 \begin{lstlisting}
166 $ export GNUNET_PREFIX=$HOME
167 $ export PATH=$PATH:$GNUNET_PREFIX/bin
168 $ echo export GNUNET_PREFIX=$HOME >> ~/.bashrc
169 $ echo export PATH=$GNUNET_PREFIX/bin:$PATH >> ~/.bashrc
170 $ mkdir ~/.gnunet/
171 $ touch ~/.gnunet/gnunet.conf
172 \end{lstlisting}
173 % $
174
175 \subsection{Common Issues - Check your GNUnet installation}
176 You should check your installation to ensure that installing GNUnet
177 was successful up to this point. You should be able to access GNUnet's
178 binaries and run GNUnet's self check.
179 \begin{lstlisting}
180 $ which gnunet-arm
181 \end{lstlisting}
182 should return \lstinline|$GNUNET_PREFIX/bin/gnunet-arm|. It should be
183 located in your GNUnet installation and the output should not be
184 empty. If you see an output like:
185 \begin{lstlisting}
186 $ which gnunet-arm
187 $
188 \end{lstlisting}
189 check your {\tt PATH} variable to ensure GNUnet's {\tt bin} directory is included.
190
191 GNUnet provides tests for all of it's subcomponents. Run
192 \begin{lstlisting}
193 $ make check
194 \end{lstlisting}
195 to execute tests for all components. {\tt make check} traverses all subdirectories in {\tt src}.
196 For every subdirectory you should get a message like this:
197
198 \begin{lstlisting}
199 make[2]: Entering directory `/home/mwachs/gnunet/contrib'
200 PASS: test_gnunet_prefix
201 =============
202 1 test passed
203 =============
204 \end{lstlisting}
205
206 If you see a message like this:
207
208 \begin{lstlisting}
209 Mar 12 16:57:56-642482 resolver-api-19449 ERROR Must specify `HOSTNAME' for `resolver' in configuration!
210 Mar 12 16:57:56-642573 test_program-19449 ERROR Assertion failed at resolver_api.c:204.
211 /bin/bash: line 5: 19449 Aborted                 (core dumped) ${dir}$tst
212 FAIL: test_program
213 \end{lstlisting}
214 double check your {\tt GNUNET\_PREFIX} environmental variable and double check the steps performed in ~\ref{sub:install}
215
216 \section{Background: GNUnet Architecture}
217 GNUnet is organized in layers and services. Each service is composed of a
218 main service implementation and a client library for other programs to use
219 the service's functionality, described by an API. This approach is shown in
220 figure~\ref{fig:service}. Some services provide an additional command line
221 tool to enable the user to interact with the service.
222
223 Very often it is other GNUnet services that will use these APIs to build the
224 higher layers of GNUnet on top of the lower ones. Each layer expands or extends
225 the functionality of the service below (for instance, to build a mesh on top of
226 a DHT). See figure ~\ref{fig:interaction} for an illustration of this approach.
227
228 \begin{figure}[!h]
229   \begin{center}
230 %  \begin{subfigure}
231         \begin{subfigure}[b]{0.3\textwidth}
232                 \centering
233                 \includegraphics[width=\textwidth]{figs/Service.pdf}
234                 \caption{Service with API and network protocol}
235                 \label{fig:service}
236         \end{subfigure}
237         ~~~~~~~~~~
238         \begin{subfigure}[b]{0.3\textwidth}
239                 \centering
240                 \includegraphics[width=\textwidth]{figs/System.pdf}
241                 \caption{Service interaction}
242                 \label{fig:interaction}
243         \end{subfigure}
244   \end{center}
245   \caption{GNUnet's layered system architecture}
246 \end{figure}
247
248 The main service implementation runs as a standalone process in the operating
249 system and the client code runs as part of the client program, so crashes of a
250 client do not affect the service process or other clients. The service and the
251 clients communicate via a message protocol to be defined and implemented by
252 the programmer.
253
254 \section{First Steps with GNUnet}
255
256 \subsection{Configure your peer}
257 First of all we need to configure your peer. Each peer is started with a configuration containing settings for GNUnet itself and it's services. This configuration is based on the default configuration shipped with GNUnet and can be modified. The default configuration is located in the {\tt \$GNUNET\_PREFIX/share/gnunet/config.d} directory. When starting a peer, you can specify a customized configuration using the the {\tt$-c$} command line switch when starting the ARM service and all other services. When using a modified configuration the default values are loaded and only values specified in the configuration file will replace the default values.
258
259 Since we want to start additional peers later, we need
260 some modifications from the default configuration. We need to create a separate service home and a file containing our modifications for this peer:
261 \begin{lstlisting}
262 $ mkdir ~/gnunet1/
263 $ touch peer1.conf
264 \end{lstlisting}
265
266 Now add the following lines to peer1.conf to use this directory. For
267 simplified usage we want to prevent the peer to connect to the GNUnet
268 network since this could lead to confusing output. This modifications
269 will replace the default settings:
270 \begin{lstlisting}
271 [PATHS]
272 GNUNET_HOME = ~/gnunet1/ # Use this directory to store GNUnet data
273 [hostlist]
274 SERVERS = # prevent bootstrapping
275 \end{lstlisting}
276
277 \subsection{Start a peer}
278 Each GNUnet instance (called peer) has an identity (\textit{peer ID}) based on a
279 cryptographic public private key pair. The peer ID is the printable hash of the
280 public key. So before starting the peer, you may want to just generate the peer's private
281 key using the command
282 \lstset{language=bash}
283 \begin{lstlisting}
284 $ gnunet-peerinfo -c ~/peer1.conf -s
285 \end{lstlisting}
286 You should see an output containing the peer ID similar to:
287 \lstset{language=bash}
288 \begin{lstlisting}
289 I am peer `0PA02UVRKQTS2C .. JL5Q78F6H0B1ACPV1CJI59MEQUMQCC5G'.
290 \end{lstlisting}
291
292 GNUnet services are controlled by a master service the so called \textit{Automatic Restart Manager} (ARM).
293 ARM starts, stops and even restarts services automatically or on demand when a client connects.
294 You interact with the ARM service using the \lstinline|gnunet-arm| tool.
295 GNUnet can then be started with \lstinline|gnunet-arm -s| and stopped with
296 \lstinline|gnunet-arm -e|.  An additional service not automatically started
297 can be started using \lstinline|gnunet-arm -i <service name>| and stopped
298 using \lstinline|gnunet-arm -k <servicename>|.
299
300 \subsection{Monitor a peer}
301 In this section, we will monitor the behaviour of our peer's DHT service with respect to a
302 specific key. First we will start GNUnet and then start the DHT service and use the DHT monitor tool
303 to monitor the PUT and GET commands we issue ussing the \lstinline|gnunet-dht-put| and
304 \lstinline|gnunet-dht-get| command. Using the ``monitor'' line given below, you can observe the behavior of
305 your own peer's DHT with respect to the specified KEY:
306
307 \lstset{language=bash}
308 \begin{lstlisting}
309 $ gnunet-arm -c ~/peer1.conf -s # start gnunet with all default services
310 $ gnunet-arm -c ~/peer1.conf -i dht # start DHT service
311 $ cd ~/gnunet/src/dht;
312 $ ./gnunet-dht-monitor -c ~/peer1.conf -k KEY
313 \end{lstlisting}
314 Now open a separate terminal and change again to the \lstinline|gnunet/src/dht| directory:
315 \begin{lstlisting}
316 $ cd ~/gnunet/src/dht
317 $ ./gnunet-dht-put -c ~/peer1.conf -k KEY -d VALUE # put VALUE under KEY in the DHT
318 $ ./gnunet/src/dht/gnunet-dht-get -c ~/peer1.conf -k KEY # get key KEY from the DHT
319 $ gnunet-statistics -c ~/peer1.conf # print statistics about current GNUnet state
320 $ gnunet-statistics -c ~/peer1.conf -s dht # print statistics about DHT service
321 \end{lstlisting}
322 % $
323 \subsection{Starting Two Peers by Hand}
324 \subsubsection{Setup a second peer}
325 We will now start a second peer on your machine.
326 For the second peer, you will need to manually create a modified
327 configuration file to avoid conflicts with ports and directories.
328 A peers configuration file is by default located in {\tt ~/.gnunet/gnunet.conf}.
329 This file is typically very short or even empty as only the differences to the
330 defaults need to be specified.  The defaults are located in
331 many files in the {\tt \$GNUNET\_PREFIX/share/gnunet/config.d} directory.
332
333 To configure the second peer, use the files {\tt
334   \$GNUNET\_PREFIX/share/gnunet/config.d} as a template for your main
335 configuration file:
336 %
337 \lstset{language=bash}
338 \begin{lstlisting}
339 $ cat $GNUNET_PREFIX/share/gnunet/config.d/*.conf > peer2.conf
340 \end{lstlisting}
341 Now you have to edit {\tt peer2.conf} and change:
342 \begin{itemize}
343   \itemsep0em
344   \item{\texttt{SERVICEHOME} under \texttt{PATHS}}
345   \item{Every (uncommented) value for ``\texttt{PORT}'' (add 10000) in any
346         section (the option may be commented out if \texttt{PORT} is
347         prefixed by "\#", in this case, UNIX domain sockets are used
348         and the PORT option does not need to be touched) }
349   \item{Every value for ``\texttt{UNIXPATH}'' in any section (e.g. by adding a "-p2" suffix)}
350 \end{itemize}
351 to a fresh, unique value.  Make sure that the \texttt{PORT} numbers stay
352 below 65536.  From now on, whenever you interact with the second
353 peer, you need to specify {\tt -c peer2.conf} as an additional
354 command line argument.
355
356 Now, generate the 2nd peer's private key:
357
358 \lstset{language=bash}
359 \begin{lstlisting}
360 $ gnunet-peerinfo -s -c peer2.conf
361 \end{lstlisting}
362 % $
363
364 This may take a while, generate entropy using your keyboard or mouse
365 as needed.  Also, make sure the output is different from the {\tt
366   gnunet-peerinfo} output for the first peer (otherwise you made an
367 error in the configuration).
368
369 \subsubsection{Start the second peer and connect the peers}
370 Then, you can start a second peer using:
371 \lstset{language=bash}
372 \begin{lstlisting}
373 $ gnunet-arm -c peer2.conf -s
374 $ gnunet-arm -c peer2.conf -i dht
375 $ ~/gnunet/src/dht/gnunet-dht-put -c peer2.conf -k KEY -d VALUE
376 $ ~/gnunet/src/dht/gnunet-dht-get -c peer2.conf -k KEY
377 \end{lstlisting}
378 If you want the two peers to connect, you have multiple options:
379 \begin{itemize}
380 \itemsep0em
381   \item UDP neighbour discovery (automatic)
382   \item Setup a bootstrap server
383   \item Connect manually
384 \end{itemize}
385 To setup peer 1 as bootstrapping server change the configuration of
386 the first one to be a hostlist server by adding the following lines to
387 \texttt{peer1.conf} to enable bootstrapping server:
388  \begin{lstlisting}
389 [hostlist]
390 OPTIONS = -p
391 \end{lstlisting}
392
393 Then change {\tt peer2.conf} and replace the ``\texttt{SERVERS}'' line in the ``\texttt{[hostlist]}'' section with
394 ``\texttt{http://localhost:8080/}''.  Restart both peers using:
395 \begin{lstlisting}
396 $ gnunet-arm -c peer1.conf -e # stop first peer
397 $ gnunet-arm -c peer1.conf -s # start first peer
398 $ gnunet-arm -c peer2.conf -s # start second peer
399 \end{lstlisting}
400
401 Note that if you start your peers without changing these settings, they
402 will use the ``global'' hostlist servers of the GNUnet P2P network and
403 likely connect to those peers.  At that point, debugging might become
404 tricky as you're going to be connected to many more peers and would
405 likely observe traffic and behaviors that are not explicitly controlled
406 by you.
407
408 \subsubsection{How to connect manually}
409 If you want to use the \texttt{peerinfo} tool to connect your peers, you should:
410 \begin{itemize}
411 \itemsep0em
412  \item{Remove {\tt hostlist} from {\tt DEFAULTSERVICES} (to not connect to the global GNUnet)}
413  \item{Start both peers running {\tt gnunet-arm -c peer1.conf -s} and {\tt gnunet-arm -c peer2.conf -s}}
414  \item{Get \texttt{HELLO} message of the first peer running {\tt gnunet-peerinfo -c peer1.conf -g}}
415  \item{Give the output to the second peer by running {\tt gnunet-peerinfo -c peer2.conf -p '<output>'}}
416 \end{itemize}
417
418 Check that they are connected using {\tt gnunet-core -c peer1.conf}, which should give you the other peer's
419 peer identity:
420 \begin{lstlisting}
421 $ gnunet-core -c peer1.conf
422 Peer `9TVUCS8P5A7ILLBGO6JSTSSN2B44H3D2MUIFJMLKAITC0I22UVFBFP1H8NRK2IA35VKAK16LLO0MFS7TAQ9M1KNBJ4NGCHP3JPVULDG'
423 \end{lstlisting}
424
425 \subsection{Starting Peers Using the Testbed Service}
426
427 GNUnet's testbed service is used for testing scenarios where a number of peers
428 are to be started.  The testbed can manage peers on a single host or on multiple
429 hosts in a distributed fashion.  On a single affordable computer, it should be
430 possible to run around tens of peers without drastically increasing the load on the
431 system.
432
433 The testbed service can be access through its API
434 \texttt{include/gnunet\_testbed\_service.h}.  The API provides many routines for
435 managing a group of peers.  It also provides a helper function
436 \texttt{GNUNET\_TESTBED\_test\_run()} to quickly setup a minimalistic testing
437 environment on a single host.
438
439 This function takes a configuration file which will be used as a template
440 configuration for the peers.  The testbed takes care of modifying relevant
441 options in the peers' configuration such as SERVICEHOME, PORT, UNIXPATH to
442 unique values so that peers run without running into conflicts.  It also checks
443 and assigns the ports in configurations only if they are free.
444
445 Additionally, the testbed service also reads its options from the same
446 configuration file.  Various available options and details about them can be
447 found in the testbed default configuration file \texttt{src/testbed/testbed.conf}.
448
449 With the testbed API, a sample test case can be structured as follows:
450 \lstinputlisting[language=C]{testbed_test.c}
451 The source code for the above listing can be found at
452 \url{https://gnunet.org/svn/gnunet/doc/testbed_test.c}.  After installing GNUnet, the above source code can be compiled as:
453 \lstset{language=bash}
454 \begin{lstlisting}
455 $ export CPPFLAGS="-I/path/to/gnunet/headers"
456 $ export LDFLAGS="-L/path/to/gnunet/libraries"
457 $ gcc $CPPFLAGS $LDFLAGS -o testbed-test testbed_test.c  -lgnunettestbed -lgnunetdht -lgnunetutil
458 \end{lstlisting}
459 The \texttt{CPPFLAGS} and \texttt{LDFLAGS} are necessary if GNUnet is installed
460 into a different directory other than \texttt{/usr/local}.
461
462 All of testbed API's peer management functions treat management actions as
463 operations and return operation handles.  It is expected that the operations
464 begin immediately, but they may get delayed (to balance out load on the system).
465 The program using the API then has to take care of marking the operation as
466 ``done'' so that its associated resources can be freed immediately and other
467 waiting operations can be executed.  Operations will be canceled if they are
468 marked as ``done'' before their completion.
469
470 An operation is treated as completed when it succeeds or fails.  Completion of
471 an operation is either conveyed as events through \textit{controller event
472   callback} or through respective operation completion callbacks.  In functions
473 which support completion notification through both controller event callback and
474 operation completion callback, first the controller event callback will be
475 called.  If the operation is not marked as done in that callback or if the
476 callback is given as NULL when creating the operation, the operation completion
477 callback will be called.  The API documentation shows which event are to be
478 expected in the controller event notifications.  It also documents any
479 exceptional behaviour.
480
481 Once the peers are started, test cases often need to connect some of the peers'
482 services.  Normally, opening a connect to a peer's service requires the peer's
483 configuration.  While using testbed, the testbed automatically generates
484 per-peer configuration.  Accessing those configurations directly through file
485 system is discouraged as their locations are dynamically created and will be
486 different among various runs of testbed.  To make access to these configurations
487 easy, testbed API provides the function
488 \texttt{GNUNET\_TESTBED\_service\_connect()}.  This function fetches the
489 configuration of a given peer and calls the \textit{Connect Adapter}.
490 In the example code, it is the \texttt{dht\_ca}.  A connect adapter is expected
491 to open the connection to the needed service by using the provided configuration
492 and return the created service connection handle.  Successful connection to the
493 needed service is signaled through \texttt{service\_connect\_comp\_cb}.
494
495 A dual to connect adapter is the \textit{Disconnect Adapter}.  This callback is
496 called after the connect adapter has been called when the operation from
497 \texttt{GNUNET\_TESTBED\_service\_connect()} is marked as ``done''.  It has to
498 disconnect from the service with the provided service handle (\texttt{op\_result}).
499
500 \exercise{Find out how many peers you can run on your system.}
501
502 \exercise{Find out how to create a 2D torus topology by changing the
503   options in the configuration file.\footnote{See \url{https://gnunet.org/content/supported-topologies}}
504   Then use the DHT API to store and retrieve values in the
505   network.}
506
507 \section{Developing Applications}
508 \subsection{gnunet-ext}
509 To develop a new peer-to-peer application or to extend GNUnet we provide
510 a template build system for writing GNUnet extensions in C. It can be
511 obtained as follows:
512
513 \lstset{language=bash}
514 \begin{lstlisting}
515 $ svn checkout https://gnunet.org/svn/gnunet-ext/
516 $ cd gnunet-ext/
517 $ ./bootstrap
518 $ ./configure --prefix=$HOME --with-gnunet=$GNUNET_PREFIX
519 $ make
520 $ make install
521 $ make check
522 \end{lstlisting}
523 % $
524
525 The GNUnet ext template includes examples and a working buildsystem for a new GNUnet service.
526 A common GNUnet service consists of the following parts which will be discussed in detail in the
527 remainder of this document. The functionality of a GNUnet service is implemented in:
528
529 \begin{itemize}
530 \itemsep0em
531   \item the GNUnet service (\lstinline|gnunet-ext/src/ext/gnunet-service-ext.c|)
532   \item the client API (\lstinline|gnunet-ext/src/ext/ext_api.c|)
533   \item the client application using the service API (\lstinline|gnunet-ext/src/ext/gnunet-ext.c|)
534
535
536 \end{itemize}
537
538 The interfaces for these entities are defined in:
539 \begin{itemize}
540 \itemsep0em
541   \item client API interface (\lstinline|gnunet-ext/src/ext/ext.h|)
542   \item the service interface (\lstinline|gnunet-ext/src/include/gnunet_service_SERVICE.h|)
543   \item the P2P protocol (\lstinline|gnunet-ext/src/include/gnunet_protocols_ext.h|)
544 \end{itemize}
545
546
547 In addition the \texttt{ext} systems provides:
548 \begin{itemize}
549 \itemsep0em
550   \item a test testing the API (\lstinline|gnunet-ext/src/ext/test_ext_api.c|)
551   \item a configuration template for the service (\lstinline|gnunet-ext/src/ext/ext.conf.in|)
552 \end{itemize}
553
554
555 \subsection{Adapting the Template}
556
557 The first step for writing any extension with a new service is to
558 ensure that the {\tt ext.conf.in} file contains entries for the
559 \texttt{UNIXPATH}, \texttt{PORT} and \texttt{BINARY} for the service in a section named after
560 the service.
561
562 If you want to adapt the template rename the {\tt ext.conf.in} to match your
563 services name, you have to modify the \texttt{AC\_OUTPUT} section in {\tt configure.ac}
564 in the \texttt{gnunet-ext} root.
565
566 \section{Writing a Client Application}
567
568 When writing any client application (for example, a command-line
569 tool), the basic structure is to start with the {\tt
570   GNUNET\_PROGRAM\_run} function.  This function will parse
571 command-line options, setup the scheduler and then invoke the {\tt
572   run} function (with the remaining non-option arguments) and a handle
573 to the parsed configuration (and the configuration file name that was
574 used, which is typically not needed):
575
576 \lstset{language=c}
577 \begin{lstlisting}
578 #include <gnunet/platform.h>
579 #include <gnunet/gnunet_util_lib.h>
580
581 static int ret;
582
583 static void
584 run (void *cls,
585      char *const *args,
586      const char *cfgfile,
587      const struct GNUNET_CONFIGURATION_Handle *cfg)
588 {
589   /* main code here */
590   ret = 0;
591 }
592
593 int
594 main (int argc, char *const *argv)
595 {
596   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
597     GNUNET_GETOPT_OPTION_END
598   };
599   return (GNUNET_OK ==
600           GNUNET_PROGRAM_run (argc,
601                               argv,
602                               "binary-name",
603                               gettext_noop ("binary description text"),
604                               options, &run, NULL)) ? ret : 1;
605 }
606 \end{lstlisting}
607
608 \subsection{Handling command-line options}
609
610 Options can then be added easily by adding global variables and
611 expanding the {\tt options} array.  For example, the following would
612 add a string-option and a binary flag (defaulting to {\tt NULL} and
613 {\tt GNUNET\_NO} respectively):
614
615 \begin{lstlisting}
616 static char *string_option;
617 static int a_flag;
618
619 // ...
620   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
621   {'s', "name", "SOMESTRING",
622      gettext_noop ("text describing the string_option NAME"), 1,
623      &GNUNET_GETOPT_set_string, &string_option},
624     {'f', "flag", NULL,
625      gettext_noop ("text describing the flag option"), 0,
626      &GNUNET_GETOPT_set_one, &a_flag},
627     GNUNET_GETOPT_OPTION_END
628   };
629   string_option = NULL;
630   a_flag = GNUNET_SYSERR;
631 // ...
632 \end{lstlisting}
633
634 Issues such as displaying some helpful text describing options using
635 the {\tt --help} argument and error handling are taken care of when
636 using this approach.  Other {\tt GNUNET\_GETOPT\_}-functions can be used
637 to obtain integer value options, increment counters, etc.  You can
638 even write custom option parsers for special circumstances not covered
639 by the available handlers. To check if an argument was specified by the
640 user you initialize the variable with a specific value (e.g. NULL for
641 a string and GNUNET\_SYSERR for a integer) and check after parsing
642 happened if the values were modified.
643
644 Inside the {\tt run} method, the program would perform the
645 application-specific logic, which typically involves initializing and
646 using some client library to interact with the service.  The client
647 library is supposed to implement the IPC whereas the service provides
648 more persistent P2P functions.
649
650 \exercise{Add a few command-line options and print them inside
651 of {\tt run}.  What happens if the user gives invalid arguments?}
652
653 \subsection{Writing a Client Library}
654
655 The first and most important step in writing a client library is to
656 decide on an API for the library.  Typical API calls include
657 connecting to the service, performing application-specific requests
658 and cleaning up.  Many examples for such service APIs can be found
659 in the {\tt gnunet/src/include/gnunet\_*\_service.h} files.
660
661 Then, a client-service protocol needs to be designed.  This typically
662 involves defining various message formats in a header that will be
663 included by both the service and the client library (but is otherwise
664 not shared and hence located within the service's directory and not
665 installed by {\tt make install}).  Each message must start with a {\tt
666   struct GNUNET\_MessageHeader} and must be shorter than 64k.  By
667 convention, all fields in IPC (and P2P) messages must be in big-endian
668 format (and thus should be read using {\tt ntohl} and similar
669 functions and written using {\tt htonl} and similar functions).
670 Unique message types must be defined for each message struct in the
671 {\tt gnunet\_protocols.h} header (or an extension-specific include
672 file).
673
674 \subsubsection{Connecting to the Service}
675
676 Before a client library can implement the application-specific protocol
677 with the service, a connection must be created:
678
679 \lstset{language=c}
680 \begin{lstlisting}
681   struct GNUNET_CLIENT_Connection *client;
682   client = GNUNET_CLIENT_connect ("service-name", cfg);
683 \end{lstlisting}
684
685 As a result a {\tt GNUNET\_CLIENT\_Connection} handle is returned
686 which has to used in later API calls related to this service.
687 The complete client API can be found in {\tt gnunet\_client\_lib.h}
688
689 \subsubsection{GNUnet Messages}
690
691 In GNUnet, messages are always sent beginning with a {\tt struct GNUNET\_MessageHeader}
692 in big endian format. This header defines the size and the type of the
693 message, the payload follows after this header.
694
695 \lstset{language=c}
696 \begin{lstlisting}
697 struct GNUNET_MessageHeader
698 {
699
700   /**
701    * The length of the struct (in bytes, including the length field itself),
702    * in big-endian format.
703    */
704   uint16_t size GNUNET_PACKED;
705
706   /**
707    * The type of the message (GNUNET_MESSAGE_TYPE_XXXX), in big-endian format.
708    */
709   uint16_t type GNUNET_PACKED;
710
711 };
712 \end{lstlisting}
713
714 Existing message types are defined in {\tt gnunet\_protocols.h}\\
715 A common way to create a message is:
716
717 \lstset{language=c}
718 \begin{lstlisting}
719 struct GNUNET_MessageHeader *msg =
720   GNUNET_malloc(payload_size + sizeof(struct GNUNET_MessageHeader));
721 msg->size = htons(payload_size + sizeof(struct GNUNET_MessageHeader));
722 msg->type = htons(GNUNET_MY_MESSAGE_TYPE);
723 memcpy(&msg[1], &payload, payload_size);
724 // use 'msg'
725 \end{lstlisting}
726
727 \exercise{Define a message struct that includes a 32-bit
728 unsigned integer in addition to the standard GNUnet MessageHeader.
729 Add a C struct and define a fresh protocol number for your message.
730 (Protocol numbers in gnunet-ext are defined in \lstinline|gnunet-ext/src/include/gnunet_protocols_ext.h|)}
731
732
733 \subsubsection{Sending Requests to the Service}
734
735 Any client-service protocol must start with the client sending the
736 first message to the service, since services are only notified about
737 (new) clients upon receiving a the first message.
738
739 Clients can transmit messages to the service using the
740 {\tt GNUNET\_CLIENT\_notify\_transmit\_ready} API:
741 \lstset{language=c}
742 \begin{lstlisting}
743 static size_t
744 transmit_cb (void *cls, size_t size, void *buf)
745 {
746   // ...
747   if (NULL == buf) { /* handle error here */; return 0; }
748   GNUNET_assert (size >= msg_size);
749   memcpy (buf, my_msg, msg_size);
750   // ...
751   return msg_size;
752 }
753
754 // ...
755 th = GNUNET_CLIENT_notify_transmit_ready (client,
756                                           msg_size,
757                                     timeout,
758                                           GNUNET_YES,
759                                           &transmit_cb, cls);
760 // ...
761 \end{lstlisting}
762
763 The client-service protocoll calls {\tt GNUNET\_CLIENT\_notify\_transmit\_ready}
764 to be notified when the client is ready to send data to the service.
765 Besides other arguments, you have to pass the client returned
766 from the {\tt connect} call, the message size and the callback function to
767 call when the client is ready to send.
768
769 Only a single transmission request can be queued per client at the
770 same time using this API.  The handle {\tt th} can be used to cancel
771 the request if necessary (for example, during shutdown).
772
773 When {\tt transmit\_cb} is called the message is copied in the buffer provided and
774 the number of bytes copied into the buffer is returned. {\tt transmit\_cb}
775 could also return 0 if for some reason no message
776 could be constructed; this is not an error and the connection to the
777 service will persist in this case.
778
779 \exercise{Define a helper function to transmit a 32-bit
780 unsigned integer (as payload) to a service using some given client
781 handle.}
782
783
784 \subsubsection{Receiving Replies from the Service}
785
786 Clients can receive messages from the service using the
787 {\tt GNUNET\_CLIENT\_receive} API:
788
789 \lstset{language=c}
790 \begin{lstlisting}
791 /**
792  * Function called with messages from stats service.
793  *
794  * @param cls closure
795  * @param msg message received, NULL on timeout or fatal error
796  */
797 static void
798 receive_message (void *cls, const struct GNUNET_MessageHeader *msg)
799 {
800   struct MyArg *arg = cls;
801
802   // process 'msg'
803 }
804
805 // ...
806   GNUNET_CLIENT_receive (client,
807                          &receive_message,
808                          arg,
809                          timeout);
810 // ...
811 \end{lstlisting}
812
813 It should be noted that this receive call only receives a single
814 message.  To receive additional messages, {\tt
815   GNUNET\_CLIENT\_receive} must be called again.
816
817 \exercise{Expand your helper function to receive a
818 response message (for example, containing just the GNUnet MessageHeader
819 without any payload).  Upon receiving the service's response, you should
820 call a callback provided to your helper function's API.  You'll need to
821 define a new 'struct' to hold your local context (``closure'').}
822
823
824 \subsection{Writing a user interface}
825
826 Given a client library, all it takes to access a service now is to
827 combine calls to the client library with parsing command-line
828 options.
829
830 \exercise{Call your client API from your {\tt run} method
831 in your client application to send a request to the service.
832 For example, send a 32-bit integer value based on a number given
833 at the command-line to the service.}
834
835
836
837 \section{Writing a Service}
838
839 Before you can test the client you've written so far, you'll need to also
840 implement the corresponding service.
841
842
843 \subsection{Code Placement}
844
845 New services are placed in their own subdirectory under {\tt gnunet/src}.
846 This subdirectory should contain the API implementation file {\tt SERVICE\_api.c},
847 the description of the client-service protocol {\tt SERVICE.h} and P2P protocol
848 {\tt SERVICE\_protocol.h}, the implementation of the service itself
849 {\tt gnunet-service-SERVICE.h} and several files for tests, including test code
850 and configuration files.
851
852 \subsection{Starting a Service}
853
854 The key API definitions for starting services are:
855 \lstset{language=C}
856 \begin{lstlisting}
857 typedef void (*GNUNET_SERVICE_Main) (void *cls,
858                                      struct GNUNET_SERVER_Handle *server,
859                                      const struct GNUNET_CONFIGURATION_Handle *cfg);
860 int GNUNET_SERVICE_run (int argc,
861                         char *const *argv,
862                         const char *serviceName,
863                         enum GNUNET_SERVICE_Options opt,
864                         GNUNET_SERVICE_Main task,
865                         void *task_cls);
866 \end{lstlisting}
867
868 Here is a starting point for your main function for your service:
869
870 \lstset{language=c}
871 \begin{lstlisting}
872 static void my_main (void *cls,
873                      struct GNUNET_SERVER_Handle *server,
874                      const struct GNUNET_CONFIGURATION_Handle *cfg)
875 {
876    /* do work */
877 }
878
879 int main (int argc, char *const*argv)
880 {
881   if (GNUNET_OK !=
882       GNUNET_SERVICE_run (argc, argv, "my",
883                           GNUNET_SERVICE_OPTION_NONE,
884                           &my_main, NULL);
885     return 1;
886   return 0;
887 }
888 \end{lstlisting}
889
890 \exercise{Write a stub service that processes no messages at all
891 in your code.  Create a default configuration for it, integrate it
892 with the build system and start the service from {\tt
893   gnunet-service-arm} using {\tt gnunet-arm -i NAME}.}
894
895
896 \subsection{Receiving Requests from Clients}
897
898 Inside of the {\tt my\_main} method, a service typically registers for
899 the various message types from clients that it supports by providing
900 a handler function, the message type itself and possibly a fixed
901 message size (or 0 for variable-size messages):
902
903 \lstset{language=c}
904 \begin{lstlisting}
905 static void
906 handle_set (void *cls,
907             struct GNUNET_SERVER_Client *client,
908             const struct GNUNET_MessageHeader *message)
909 {
910   GNUNET_SERVER_receive_done (client, GNUNET_OK);
911 }
912 static void
913 handle_get (void *cls,
914             struct GNUNET_SERVER_Client *client,
915             const struct GNUNET_MessageHeader *message)
916 {
917   GNUNET_SERVER_receive_done (client, GNUNET_OK);
918 }
919
920 static void my_main (void *cls,
921                      struct GNUNET_SERVER_Handle *server,
922                      const struct GNUNET_CONFIGURATION_Handle *cfg)
923 {
924   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
925     {&handle_set, NULL, GNUNET_MESSAGE_TYPE_MYNAME_SET, 0},
926     {&handle_get, NULL, GNUNET_MESSAGE_TYPE_MYNAME_GET, 0},
927     {NULL, NULL, 0, 0}
928   };
929   GNUNET_SERVER_add_handlers (server, handlers);
930    /* do more setup work */
931 }
932 \end{lstlisting}
933
934 Each handler function {\bf must} eventually (possibly in some
935 asynchronous continuation) call {\tt GNUNET\_SERVER\_receive\_done}.
936 Only after this call additional messages from the same client may
937 be processed. This way, the service can throttle processing messages
938 from the same client.  By passing {\tt GNUNET\_SYSERR}, the service
939 can close the connection to the client, indicating an error.
940
941 Services must check that client requests are well-formed and must not
942 crash on protocol violations by the clients.  Similarly, client
943 libraries must check replies from servers and should gracefully report
944 errors via their API.
945
946
947 \exercise{Change the service to ``handle'' the message from your
948 client (for now, by printing a message).  What happens if you
949 forget to call {\tt GNUNET\_SERVER\_receive\_done}?}
950
951
952 \subsection{Responding to Clients}
953
954 Servers can send messages to clients using the
955 {\tt GNUNET\_SERVER\_notify\_transmit\_ready} API:
956
957 \lstset{language=c}
958 \begin{lstlisting}
959 static size_t
960 transmit_cb (void *cls, size_t size, void *buf)
961 {
962   // ...
963   if (NULL == buf) { handle_error(); return 0; }
964   GNUNET_assert (size >= msg_size);
965   memcpy (buf, my_msg, msg_size);
966   // ...
967   return msg_size;
968 }
969
970 // ...
971 struct GNUNET_SERVER_TransmitHandle *th;
972 th = GNUNET_SERVER_notify_transmit_ready (client,
973                                           msg_size,
974                                           timeout,
975                                           &transmit_cb, cls);
976 // ...
977 \end{lstlisting}
978
979 Only a single transmission request can be queued per client
980 at the same time using this API.
981 Additional APIs for sending messages to clients can be found
982 in the {\tt gnunet\_server\_lib.h} header.
983
984
985 \exercise{Change the service respond to the request from your
986 client.  Make sure you handle malformed messages in both directions.}
987
988
989 \section{Interacting directly with other Peers using the CORE Service}
990
991 One of the most important services in GNUnet is the \texttt{CORE} service
992 managing connections between peers and handling encryption between peers.
993
994 One of the first things any service that extends the P2P protocol typically does
995 is connect to the \texttt{CORE} service using:
996
997 \lstset{language=C}
998 \begin{lstlisting}
999 #include <gnunet/gnunet_core_service.h>
1000
1001 struct GNUNET_CORE_Handle *
1002 GNUNET_CORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1003                      void *cls,
1004                      GNUNET_CORE_StartupCallback init,
1005                      GNUNET_CORE_ConnectEventHandler connects,
1006                      GNUNET_CORE_DisconnectEventHandler disconnects,
1007                      GNUNET_CORE_MessageCallback inbound_notify,
1008                      int inbound_hdr_only,
1009                      GNUNET_CORE_MessageCallback outbound_notify,
1010                      int outbound_hdr_only,
1011                      const struct GNUNET_CORE_MessageHandler *handlers);
1012 \end{lstlisting}
1013
1014 \subsection{New P2P connections}
1015
1016 Before any traffic with a different peer can be exchanged, the peer must be
1017 known to the service. This is notified by the \texttt{CORE} {\tt connects} callback,
1018 which communicates the identity of the new peer to the service:
1019
1020 \lstset{language=C}
1021 \begin{lstlisting}
1022 void
1023 connects (void *cls,
1024           const struct GNUNET_PeerIdentity * peer)
1025 {
1026     /* Save identity for later use */
1027     /* Optional: start sending messages to peer */
1028 }
1029 \end{lstlisting}
1030
1031 \exercise{Create a service that connects to the \texttt{CORE}.  Then
1032 start (and connect) two peers and print a message once your connect
1033 callback is invoked.}
1034
1035 \subsection{Receiving P2P Messages}
1036
1037 To receive messages from \texttt{CORE}, services register a set of handlers
1038 (parameter {\tt *handlers} in the \lstinline|GNUNET_CORE_connect| call that are called by \texttt{CORE}
1039 when a suitable message arrives.
1040
1041 \lstset{language=c}
1042 \begin{lstlisting}
1043 static int
1044 callback_function_for_type_one(void *cls,
1045                                const struct GNUNET_PeerIdentity *peer,
1046                                const struct GNUNET_MessageHeader *message)
1047 {
1048     /* Do stuff */
1049     return GNUNET_OK; /* or GNUNET_SYSERR to close the connection */
1050 }
1051
1052 /**
1053  * Functions to handle messages from core
1054  */
1055 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
1056   {&callback_function_for_type_one, GNUNET_MESSAGE_TYPE_MYSERVICE_TYPE_ONE, 0},
1057   /* more handlers*/
1058   {NULL, 0, 0}
1059 };
1060 \end{lstlisting}
1061
1062 \exercise{Start one peer with a new service that has a message
1063 handler and start a second peer that only has your ``old'' service
1064 without message handlers.  Which ``connect'' handlers are invoked when
1065 the two peers are connected?  Why?}
1066
1067
1068 \subsection{Sending P2P Messages}
1069
1070 In response to events (connect, disconnect, inbound messages,
1071 timing, etc.) services can then use this API to transmit messages:
1072
1073 \lstset{language=C}
1074 \begin{lstlisting}
1075 typedef size_t
1076 (*GNUNET_CONNECTION_TransmitReadyNotify) (void *cls,
1077                                           size_t size,
1078                                           void *buf)
1079 {
1080     /* Fill "*buf" with up to "size" bytes, must start with GNUNET_MessageHeader */
1081     return n; /* Total size of the message put in "*buf" */
1082 }
1083
1084 struct GNUNET_CORE_TransmitHandle *
1085 GNUNET_CORE_notify_transmit_ready (struct GNUNET_CORE_Handle *handle,
1086                                    int cork, uint32_t priority,
1087                                    struct GNUNET_TIME_Relative maxdelay,
1088                                    const struct GNUNET_PeerIdentity *target,
1089                                    size_t notify_size,
1090                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1091                                    void *notify_cls);
1092 \end{lstlisting}
1093
1094 \exercise{Write a service that upon connect sends messages as
1095 fast as possible to the other peer (the other peer should run a
1096 service that ``processes'' those messages).  How fast is the
1097 transmission?  Count using the STATISTICS service on both ends.  Are
1098 messages lost? How can you transmit messages faster?  What happens if
1099 you stop the peer that is receiving your messages?}
1100
1101
1102 \subsection{End of P2P connections}
1103
1104 If a message handler returns {\tt GNUNET\_SYSERR}, the remote peer shuts down or
1105 there is an unrecoverable network disconnection, CORE notifies the service that
1106 the peer disconnected. After this notification no more messages will be received
1107 from the peer and the service is no longer allowed to send messages to the peer.
1108 The disconnect callback looks like the following:
1109
1110 \lstset{language=C}
1111 \begin{lstlisting}
1112 void
1113 disconnects (void *cls,
1114              const struct GNUNET_PeerIdentity * peer)
1115 {
1116     /* Remove peer's identity from known peers */
1117     /* Make sure no messages are sent to peer from now on */
1118 }
1119 \end{lstlisting}
1120
1121 \exercise{Fix your service to handle peer disconnects.}
1122
1123 \section{Using the DHT}
1124 The DHT allows to store data so other peers in the P2P network can
1125 access it and retrieve data stored by any peers in the network.
1126 This section will explain how to use the DHT. Of course, the first
1127 thing to do is to connect to the DHT service:
1128 \lstset{language=C}
1129 \begin{lstlisting}
1130 dht_handle = GNUNET_DHT_connect (cfg, parallel_requests);
1131 \end{lstlisting}
1132 The second parameter indicates how many requests in parallel to expect.
1133 It is not a hard limit, but a good approximation will make the DHT more
1134 efficient.
1135
1136 \subsection{Storing data in the DHT}
1137 Since the DHT is a dynamic environment (peers join and leave frequently)
1138 the data that we put in the DHT does not stay there indefinitely. It is
1139 important to ``refresh'' the data periodically by simply storing it again,
1140 in order to make sure other peers can access it.
1141
1142 The put API call offers a callback to signal that the PUT request has been
1143 sent. This does not guarantee that the data is accessible to others peers,
1144 or even that is has been stored, only that the service has requested to
1145 a neighboring peer the retransmission of the PUT request towards its final
1146 destination. Currently there is no feedback about whether or not the data
1147 has been sucessfully stored or where it has been stored. In order to improve
1148 the availablilty of the data and to compensate for possible errors, peers leaving
1149 and other unfavorable events, just make several PUT requests!
1150
1151 \lstset{language=C}
1152 \begin{lstlisting}
1153 void
1154 message_sent_cont (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1155 {
1156     /* Request has left local node */
1157 }
1158
1159 struct GNUNET_DHT_PutHandle *
1160 GNUNET_DHT_put (struct GNUNET_DHT_Handle *handle,
1161                 const struct GNUNET_HashCode * key,
1162                 uint32_t desired_replication_level,
1163                 enum GNUNET_DHT_RouteOption options, /* Route options, see next call */
1164                 enum GNUNET_BLOCK_Type type, size_t size, const void *data,
1165                 struct GNUNET_TIME_Absolute exp, /* When does the data expire? */
1166                 struct GNUNET_TIME_Relative timeout,  /* How long to try to send the request */
1167                 GNUNET_DHT_PutContinuation cont,
1168                 void *cont_cls)
1169 \end{lstlisting}
1170
1171 \exercise{Store a value in the DHT periodically to make sure it is available
1172 over time. You might consider using the function GNUNET\_SCHEDULER\_add\_delayed and
1173 call GNUNET\_DHT\_put from inside a helper function.}
1174
1175
1176 \subsection{Obtaining data from the DHT}
1177 As we saw in the previous example, the DHT works in an asynchronous mode.
1178 Each request to the DHT is executed ``in the background'' and the API
1179 calls return immediately. In order to receive results from the DHT, the
1180 API provides a callback. Once started, the request runs in the service,
1181 the service will try to get as many results as possible (filtering out
1182 duplicates) until the timeout expires or we explicitly stop the request.
1183 It is possible to give a ``forever'' timeout with
1184 {\tt GNUNET\_TIME\_UNIT\_FOREVER\_REL}.
1185
1186 If we give a route option {\tt GNUNET\_DHT\_RO\_RECORD\_ROUTE} the callback
1187 will get a list of all the peers the data has travelled, both on the PUT
1188 path and on the GET path.
1189 \lstset{language=C}
1190 \begin{lstlisting}
1191 static void
1192 get_result_iterator (void *cls, struct GNUNET_TIME_Absolute expiration,
1193                      const struct GNUNET_HashCode * key,
1194                      const struct GNUNET_PeerIdentity *get_path,
1195                      unsigned int get_path_length,
1196                      const struct GNUNET_PeerIdentity *put_path,
1197                      unsigned int put_path_length,
1198                      enum GNUNET_BLOCK_Type type, size_t size, const void *data)
1199 {
1200     /* Do stuff with the data and/or route */
1201     /* Optionally: */
1202     GNUNET_DHT_get_stop (get_handle);
1203 }
1204
1205 get_handle =
1206       GNUNET_DHT_get_start (dht_handle,
1207                             block_type,
1208                             &key,
1209                             replication,
1210                             GNUNET_DHT_RO_NONE, /* Route options */
1211                             NULL, /* xquery: not used here */
1212                             0, /* xquery size */
1213                             &get_result_iterator,
1214                             cls)
1215 \end{lstlisting}
1216
1217 \exercise{Store a value in the DHT and after a while retrieve it. Show the IDs of all
1218 the peers the requests have gone through. In order to convert a peer ID to a string, use
1219 the function GNUNET\_i2s. Pay attention to the route option parameters in both calls!}
1220
1221 \subsection{Implementing a block plugin}
1222
1223 In order to store data in the DHT, it is necessary to provide a block
1224 plugin.  The DHT uses the block plugin to ensure that only well-formed
1225 requests and replies are transmitted over the network.
1226
1227 The block plugin should be put in a file {\tt
1228   plugin\_block\_SERVICE.c} in the service's respective directory. The
1229 mandatory functions that need to be implemented for a block plugin are
1230 described in the following sections.
1231
1232 \subsubsection{Validating requests and replies}
1233
1234 The evaluate function should validate a reply or a request. It returns
1235 a {\tt GNUNET\_BLOCK\_EvaluationResult}, which is an enumeration. All
1236 possible answers are in {\tt gnunet\_block\_lib.h}.  The function will
1237 be called with a {\tt reply\_block} argument of {\tt NULL} for
1238 requests.  Note that depending on how {\tt evaluate} is called, only
1239 some of the possible return values are valid.  The specific meaning of
1240 the {\tt xquery} argument is application-specific.  Applications that
1241 do not use an extended query should check that the {\tt xquery\_size}
1242 is zero.  The Bloom filter is typically used to filter duplicate
1243 replies.
1244
1245 \lstset{language=C}
1246 \begin{lstlisting}
1247 static enum GNUNET_BLOCK_EvaluationResult
1248 block_plugin_SERVICE_evaluate (void *cls,
1249                                enum GNUNET_BLOCK_Type type,
1250                                const GNUNET_HashCode * query,
1251                                struct GNUNET_CONTAINER_BloomFilter **bf,
1252                                int32_t bf_mutator,
1253                                const void *xquery,
1254                                size_t xquery_size,
1255                                const void *reply_block,
1256                                size_t reply_block_size)
1257 {
1258   /* Verify type, block and bloomfilter */
1259 }
1260 \end{lstlisting}
1261
1262 Note that it is mandatory to detect duplicate replies in this
1263 function and return the respective status code.  Duplicate
1264 detection should be done by setting the respective bits in
1265 the Bloom filter {\tt bf}.  Failure to do so may cause replies
1266 to circle in the network.
1267
1268 \subsubsection{Deriving a key from a reply}
1269
1270 The DHT can operate more efficiently if it is possible to derive a key
1271 from the value of the corresponding block.  The {\tt get\_key}
1272 function is used to obtain the key of a block --- for example, by
1273 means of hashing.  If deriving the key is not possible, the function
1274 should simply return {\tt GNUNET\_SYSERR} (the DHT will still work
1275 just fine with such blocks).
1276
1277 \lstset{language=C}
1278 \begin{lstlisting}
1279 static int
1280 block_plugin_SERVICE_get_key (void *cls, enum GNUNET_BLOCK_Type type,
1281                               const void *block, size_t block_size,
1282                               GNUNET_HashCode * key)
1283 {
1284     /* Store the key in the key argument, return GNUNET_OK on success. */
1285 }
1286 \end{lstlisting}
1287
1288 \subsubsection{Initialization of the plugin}
1289
1290 The plugin is realized as a shared C library.  The library must export
1291 an initialization function which should initialize the plugin.  The
1292 initialization function specifies what block types the plugin cares
1293 about and returns a struct with the functions that are to be used for
1294 validation and obtaining keys (the ones just defined above).
1295
1296 \lstset{language=C}
1297 \begin{lstlisting}
1298 void *
1299 libgnunet_plugin_block_SERVICE_init (void *cls)
1300 {
1301   static enum GNUNET_BLOCK_Type types[] =
1302   {
1303     GNUNET_BLOCK_TYPE_SERVICE_BLOCKYPE, /* list of blocks we care about, from gnunet_block_lib.h */
1304     GNUNET_BLOCK_TYPE_ANY       /* end of list */
1305   };
1306   struct GNUNET_BLOCK_PluginFunctions *api;
1307
1308   api = GNUNET_malloc (sizeof (struct GNUNET_BLOCK_PluginFunctions));
1309   api->evaluate = &block_plugin_SERICE_evaluate;
1310   api->get_key = &block_plugin_SERVICE_get_key;
1311   api->types = types;
1312   return api;
1313 }
1314 \end{lstlisting}
1315
1316 \subsubsection{Shutdown of the plugin}
1317
1318 Following GNUnet's general plugin API concept, the plugin must
1319 export a second function for cleaning up.  It usually does very
1320 little.
1321
1322 \lstset{language=C}
1323 \begin{lstlisting}
1324 void *
1325 libgnunet_plugin_block_SERVICE_done (void *cls)
1326 {
1327   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1328
1329   GNUNET_free (api);
1330   return NULL;
1331 }
1332 \end{lstlisting}
1333
1334
1335 \subsubsection{Integration of the plugin with the build system}
1336
1337 In order to compile the plugin, the {\tt Makefile.am} file for the
1338 service \texttt{SERVICE} should contain a rule similar to this:
1339
1340 \lstset{language=make}
1341 \begin{lstlisting}
1342   plugindir = $(libdir)/gnunet
1343
1344   plugin_LTLIBRARIES = \
1345           libgnunet_plugin_block_ext.la
1346   libgnunet_plugin_block_ext_la_SOURCES = \
1347           plugin_block_ext.c
1348   libgnunet_plugin_block_ext_la_LIBADD = \
1349           $(prefix)/lib/libgnunethello.la \
1350           $(prefix)/lib/libgnunetblock.la \
1351           $(prefix)/lib/libgnunetutil.la
1352   libgnunet_plugin_block_ext_la_LDFLAGS = \
1353           $(GN_PLUGIN_LDFLAGS)
1354   libgnunet_plugin_block_ext_la_DEPENDENCIES = \
1355           $(prefix)/lib/libgnunetblock.la
1356 \end{lstlisting}
1357 % $
1358
1359
1360 \exercise{Write a block plugin that accepts all queries
1361 and all replies but prints information about queries and replies
1362 when the respective validation hooks are called.}
1363
1364
1365
1366 \subsection{Monitoring the DHT}
1367 It is possible to monitor the functioning of the local DHT service. When monitoring
1368 the DHT, the service will alert the monitoring program of any events,
1369 both started locally or received for routing from another peer. The are three different
1370 types of events possible: a GET request, a PUT request or a response (a reply to
1371 a GET).
1372
1373 Since the different events have different associated data, the API gets 3
1374 different callbacks (one for each message type) and optional type and key parameters,
1375 to allow for filtering of messages. When an event happens, the appropiate callback
1376 is called with all the information about the event.
1377 \lstset{language=C}
1378 \begin{lstlisting}
1379 void
1380 get_callback (void *cls,
1381               enum GNUNET_DHT_RouteOption options,
1382               enum GNUNET_BLOCK_Type type,
1383               uint32_t hop_count,
1384               uint32_t desired_replication_level,
1385               unsigned int path_length,
1386               const struct GNUNET_PeerIdentity *path,
1387               const struct GNUNET_HashCode * key)
1388 {
1389 }
1390
1391 void
1392 get_resp_callback (void *cls,
1393                    enum GNUNET_BLOCK_Type type,
1394                    const struct GNUNET_PeerIdentity *get_path,
1395                    unsigned int get_path_length,
1396                    const struct GNUNET_PeerIdentity *put_path,
1397                    unsigned int put_path_length,
1398                    struct GNUNET_TIME_Absolute exp,
1399                    const struct GNUNET_HashCode * key,
1400                    const void *data,
1401                    size_t size)
1402 {
1403 }
1404
1405 void
1406 put_callback (void *cls,
1407               enum GNUNET_DHT_RouteOption options,
1408               enum GNUNET_BLOCK_Type type,
1409               uint32_t hop_count,
1410               uint32_t desired_replication_level,
1411               unsigned int path_length,
1412               const struct GNUNET_PeerIdentity *path,
1413               struct GNUNET_TIME_Absolute exp,
1414               const struct GNUNET_HashCode * key,
1415               const void *data,
1416               size_t size)
1417 {
1418 }
1419
1420 monitor_handle = GNUNET_DHT_monitor_start (dht_handle,
1421                                            block_type, /* GNUNET_BLOCK_TYPE_ANY for all */
1422                                            key, /* NULL for all */
1423                                            &get_callback,
1424                                            &get_resp_callback,
1425                                            &put_callback,
1426                                            cls);
1427 \end{lstlisting}
1428
1429
1430 \section{Debugging with {\tt gnunet-arm}}
1431
1432 Even if services are managed by {\tt gnunet-arm}, you can start them with
1433 {\tt gdb} or {\tt valgrind}.  For example, you could add the following lines
1434 to your configuration file to start the DHT service in a {\tt gdb} session in a
1435 fresh {\tt xterm}:
1436
1437 \begin{verbatim}
1438 [dht]
1439 PREFIX=xterm -e gdb --args
1440 \end{verbatim}
1441
1442 Alternatively, you can stop a service that was started via ARM and run it manually:
1443
1444 \lstset{language=bash}
1445 \begin{lstlisting}
1446 $ gnunet-arm -k dht
1447 $ gdb --args gnunet-service-dht -L DEBUG
1448 $ valgrind gnunet-service-dht -L DEBUG
1449 \end{lstlisting}
1450 % $
1451
1452 Assuming other services are well-written, they will automatically re-integrate the
1453 restarted service with the peer.
1454
1455 GNUnet provides a powerful logging mechanism providing log levels \texttt{ERROR},
1456 \texttt{WARNING}, \texttt{INFO} and \texttt{DEBUG}. The current log level is
1457 configured using the \lstinline|$GNUNET_FORCE_LOG| environmental variable.
1458 The \texttt{DEBUG} level is only available if \lstinline|--enable-logging=verbose| was used when
1459 running \texttt{configure}. More details about logging can be found under
1460 \url{https://gnunet.org/logging}.
1461
1462 You should also probably enable the creation of core files, by setting
1463 {\tt ulimit}, and echo'ing 1 into {\tt /proc/sys/kernel/core\_uses\_pid}.
1464 Then you can investigate the core dumps with {\tt gdb}, which is often
1465 the fastest method to find simple errors.
1466
1467 \exercise{Add a memory leak to your service and obtain a trace
1468 pointing to the leak using {\tt valgrind} while running the service
1469 from {\tt gnunet-service-arm}.}
1470
1471
1472 \end{document}