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