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