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