doc: gnunet-c-tutorial.texi, chapters/installation.texi: fix compilation warnings.
[oweals/gnunet.git] / doc / gnunet-c-tutorial.texi
1 \input texinfo
2 @c %**start of header
3 @setfilename gnunet-c-tutorial.info
4 @documentencoding UTF-8
5 @settitle GNUnet C Tutorial
6 @c %**end of header
7
8 @copying
9 Copyright @copyright{} 2001-2017 GNUnet e.V.
10
11 Permission is granted to copy, distribute and/or modify this document
12 under the terms of the GNU Free Documentation License, Version 1.3 or
13 any later version published by the Free Software Foundation; with no
14 Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.  A
15 copy of the license is included in the section entitled ``GNU Free
16 Documentation License''.
17
18 A copy of the license is also available from the Free Software
19 Foundation Web site at @url{http://www.gnu.org/licenses/fdl.html}.
20
21 Alternately, this document is also available under the General
22 Public License, version 3 or later, as published by the Free Software
23 Foundation.  A copy of the license is included in the section entitled
24 ``GNU General Public License''.
25
26 A copy of the license is also available from the Free Software
27 Foundation Web site at @url{http://www.gnu.org/licenses/gpl.html}.
28 @end copying
29
30 @titlepage
31 @title GNUnet C Tutorial
32 @subtitle A Tutorial for GNUnet 0.10.x (C version)
33 @author The GNUnet Developers
34
35 @page
36 @vskip 0pt plus 1filll
37
38 @insertcopying
39 @end titlepage
40
41 @contents
42
43 @c **** TODO
44 @c 1. Update content?
45 @c 2. Either reference main documentation or
46 @c 3. Merge this into main documentation
47
48 @node Top
49 @top Introduction
50
51 This tutorials explains how to install GNUnet on a GNU/Linux system and gives an introduction on how
52 GNUnet can be used to develop a Peer-to-Peer application. Detailed installation instructions for
53 various operating systems and a detailed list of all dependencies can be found on our website at
54 @uref{https://gnunet.org/installation}.
55
56 Please read this tutorial carefully since every single step is
57 important and do not hesitate to contact the GNUnet team if you have
58 any questions or problems! Check here how to contact the GNUnet
59 team: @uref{https://gnunet.org/contact_information}
60
61
62 @section Installing GNUnet
63
64 First of all you have to install a current version of GNUnet. You can download a
65 tarball of a stable version from GNU FTP mirrors or obtain the latest development
66 version from our Git repository.
67
68 Most of the time you should prefer to download the stable version since with the
69 latest development version things can be broken, functionality can be changed or tests
70 can fail. You should only use the development version if you know that you require a
71 certain feature or a certain issue has been fixed since the last release.
72
73 @subsection Obtaining a stable version
74
75 You can download the latest stable version of GNUnet from GNU FTP mirrors:
76 @uref{https://ftp.gnu.org/gnu/gnunet/gnunet-0.10.x.tar.gz}
77 You should also download the signature file and verify the integrity of the tarball.
78 @uref{https://ftp.gnu.org/gnu/gnunet/gnunet-0.10.x.tar.gz.sig}
79 To verify the signature you should first import the GPG key used to sign the tarball
80 @example
81 $ gpg --keyserver keys.gnupg.net --recv-keys 48426C7E
82 @end example
83 And use this key to verify the tarball's signature
84 @example
85 $ gpg --verify gnunet-0.10.x.tar.gz.sig gnunet-0.10.x.tar.gz
86 @end example
87 After successfully verifying the integrity you can extract the tarball using
88 @example
89 $ tar xvzf gnunet-0.10.x.tar.gz
90 ## we will use the directory "gnunet" in the remainder of this document
91 $ mv gnunet-0.10.x gnunet
92 $ cd gnunet
93 @end example
94
95 However, please note that stable versions can be very outdated, as a developer
96 you are strongly encouraged to use the version from @uref{https://gnunet.org/git/}.
97
98 @subsection Installing Build Tool Chain and Dependencies
99
100 To successfully compile GNUnet you need the tools to build GNUnet and the required dependencies.
101 Please have a look at @uref{https://gnunet.org/dependencies} for a list of required dependencies
102 and @uref{https://gnunet.org/generic_installation} for specific instructions for your operating system.
103
104 Please check the notes at the end of the configure process about required dependencies.
105
106 For GNUnet bootstrapping support and the http(s) plugin you should install libgnurl.
107 For the filesharing service you should install at least one of the datastore backends mysql,
108 sqlite or postgresql.
109
110 @subsection Obtaining the latest version from Git
111
112 The latest development version can obtained from our Git repository. To obtain
113 the code you need Git installed and checkout the repository using:
114 @example
115 $ git clone https://gnunet.org/git/gnunet
116 @end example
117 After cloning the repository you have to execute
118 @example
119 $ cd gnunet
120 $ ./bootstrap
121 @end example
122
123 The remainder of this tutorial assumes that you have Git branch ``master'' checked out.
124
125 @subsection Compiling and Installing GNUnet
126
127 First, you need to install at least libgnupgerror version 1.27
128 @uref{https://www.gnupg.org/ftp/gcrypt/libgpg-error/libgpg-error-1.27.tar.bz2}
129 and libgcrypt version 1.7.6 @uref{https://www.gnupg.org/ftp/gcrypt/libgcrypt/libgcrypt-1.7.6.tar.bz2}.
130
131 @example
132 $ wget https://www.gnupg.org/ftp/gcrypt/libgpg-error/libgpg-error-1.27.tar.bz2
133 $ tar xf libgpg-error-1.27.tar.bz2
134 $ cd libgpg-error-1.27
135 $ ./configure
136 $ sudo make install
137 $ cd ..
138 @end example
139
140 @example
141 $ wget https://www.gnupg.org/ftp/gcrypt/libgcrypt/libgcrypt-1.7.6.tar.bz2
142 $ tar xf libgcrypt-1.7.6.tar.bz2
143 $ cd libgcrypt-1.7.6
144 $ ./configure
145 $ sudo make install
146 $ cd ..
147 @end example
148
149 @subsubsection Installing GNUnet
150 Assuming all dependencies are installed, the following commands will
151 compile and install GNUnet in your home directory. You can specify the
152 directory where GNUnet will be installed by changing the
153 @code{--prefix} value when calling @command{./configure}.  If
154 you do not specifiy a prefix, GNUnet is installed in the directory
155 @file{/usr/local}. When developing new applications you may want
156 to enable verbose logging by adding @code{--enable-logging=verbose}:
157
158 @example
159 $ ./configure --prefix=$PREFIX --enable-logging
160 $ make
161 $ make install
162 @end example
163
164 After installing GNUnet you have to add your GNUnet installation to your path
165 environmental variable. In addition you have to create the @file{.config}
166 directory in your home directory (unless it already exists) where GNUnet stores
167 its data and an empty GNUnet configuration file:
168
169 @example
170 $ export PATH=$PATH:$PREFIX/bin
171 $ echo export PATH=$PREFIX/bin:\\$PATH >> ~/.bashrc
172 $ mkdir ~/.config/
173 $ touch ~/.config/gnunet.conf
174 @end example
175
176 @subsection Common Issues - Check your GNUnet installation
177
178 You should check your installation to ensure that installing GNUnet
179 was successful up to this point. You should be able to access GNUnet's
180 binaries and run GNUnet's self check.
181 @example
182 $ which gnunet-arm
183 @end example
184 should return $PREFIX/bin/gnunet-arm. It should be
185 located in your GNUnet installation and the output should not be
186 empty. If you see an output like:
187 @example
188 $ which gnunet-arm
189 @end example
190 check your PATH variable to ensure GNUnet's @file{bin} directory is included.
191
192 GNUnet provides tests for all of its subcomponents. Run
193 @example
194 $ make check
195 @end example
196 to execute tests for all components. make check traverses all subdirectories in src.
197 For every subdirectory you should get a message like this:
198
199 @example
200 make[2]: Entering directory `/home/$USER/gnunet/contrib'
201 PASS: test_gnunet_prefix
202 =============
203 1 test passed
204 =============
205 @end example
206
207 @section Background: GNUnet Architecture
208
209 GNUnet is organized in layers and services. Each service is composed of a
210 main service implementation and a client library for other programs to use
211 the service's functionality, described by an API. This approach is shown in
212 @c** FIXME: enable this once the commented block below works:
213 @c** figure~\ref{fig:service}.
214 Some services provide an additional command line tool to enable the user to
215 interact with the service.
216
217 Very often it is other GNUnet services that will use these APIs to build the
218 higher layers of GNUnet on top of the lower ones. Each layer expands or extends
219 the functionality of the service below (for instance, to build a mesh on top of
220 a DHT).
221 @c** FXIME: See comment above.
222 @c** See figure ~\ref{fig:interaction} for an illustration of this approach.
223
224 @c \begin{figure}[!h]
225 @c   \begin{center}
226 @c %  \begin{subfigure}
227 @c         \begin{subfigure}[b]{0.3\textwidth}
228 @c                 \centering
229 @c                 \includegraphics[width=\textwidth]{figs/Service.pdf}
230 @c                 \caption{Service with API and network protocol}
231 @c                 \label{fig:service}
232 @c         \end{subfigure}
233 @c         ~~~~~~~~~~
234 @c         \begin{subfigure}[b]{0.3\textwidth}
235 @c                 \centering
236 @c                 \includegraphics[width=\textwidth]{figs/System.pdf}
237 @c                 \caption{Service interaction}
238 @c                 \label{fig:interaction}
239 @c         \end{subfigure}
240 @c   \end{center}
241 @c   \caption{GNUnet's layered system architecture}
242 @c \end{figure}
243
244 The main service implementation runs as a standalone process in the operating
245 system and the client code runs as part of the client program, so crashes of a
246 client do not affect the service process or other clients. The service and the
247 clients communicate via a message protocol to be defined and implemented by
248 the programmer.
249
250
251 @section First Steps with GNUnet
252
253 @subsection Configure your peer
254
255 First of all we need to configure your peer. Each peer is started with a configuration
256 containing settings for GNUnet itself and its services. This configuration is based on the
257 default configuration shipped with GNUnet and can be modified. The default configuration
258 is located in the @file{$PREFIX/share/gnunet/config.d} directory. When starting a peer, you
259 can specify a customized configuration using the the @command{-c} command line switch when
260 starting the ARM service and all other services. When using a modified configuration the
261 default values are loaded and only values specified in the configuration file will replace
262 the default values.
263
264 Since we want to start additional peers later, we need some modifications from the default
265 configuration. We need to create a separate service home and a file containing our
266 modifications for this peer:
267 @example
268 $ mkdir ~/gnunet1/
269 $ touch peer1.conf
270 @end example
271
272 Now add the following lines to @file{peer1.conf} to use this directory. For
273 simplified usage we want to prevent the peer to connect to the GNUnet
274 network since this could lead to confusing output. This modifications
275 will replace the default settings:
276 @example
277 [PATHS]
278 GNUNET_HOME = ~/gnunet1/  # Use this directory to store GNUnet data
279 [hostlist]
280 SERVERS =                 # prevent bootstrapping
281 @end example
282
283 @subsection Start a peer
284 Each GNUnet instance (called peer) has an identity (peer ID) based on a
285 cryptographic public private key pair. The peer ID is the printable hash of the
286 public key.
287
288 GNUnet services are controlled by a master service, the so called @dfn{Automatic Restart Manager} (ARM).
289 ARM starts, stops and even restarts services automatically or on demand when a client connects.
290 You interact with the ARM service using the gnunet-arm tool.
291 GNUnet can then be started with @command{gnunet-arm -s} and stopped with
292 @command{gnunet-arm -e}.  An additional service not automatically started
293 can be started using @command{gnunet-arm -i <service name>} and stopped
294 using @command{gnunet-arm -k <servicename>}.
295
296 Once you have started your peer, you can use many other GNUnet commands
297 to interact with it.  For example, you can run:
298 @example
299 $ gnunet-peerinfo -s
300 @end example
301 to obtain the public key of your peer.
302 You should see an output containing the peer ID similar to:
303 @example
304 I am peer `0PA02UVRKQTS2C .. JL5Q78F6H0B1ACPV1CJI59MEQUMQCC5G'.
305 @end example
306
307
308 @subsection Monitor a peer
309
310 In this section, we will monitor the behaviour of our peer's DHT service with respect to a
311 specific key. First we will start GNUnet and then start the DHT service and use the DHT monitor tool
312 to monitor the PUT and GET commands we issue ussing the @command{gnunet-dht-put} and
313 @command{gnunet-dht-get} commands. Using the ``monitor'' line given below, you can observe
314 the behavior of your own peer's DHT with respect to the specified KEY:
315
316 @example
317 $ gnunet-arm -c ~/peer1.conf -s                 # start gnunet with all default services
318 $ gnunet-arm -c ~/peer1.conf -i dht             # start DHT service
319 $ cd ~/gnunet/src/dht;
320 $ ./gnunet-dht-monitor -c ~/peer1.conf -k KEY
321 @end example
322 Now open a separate terminal and change again to the @file{gnunet/src/dht} directory:
323 @example
324 $ cd ~/gnunet/src/dht
325 $ ./gnunet-dht-put -c ~/peer1.conf -k KEY -d VALUE              # put VALUE under KEY in the DHT
326 $ ./gnunet/src/dht/gnunet-dht-get -c ~/peer1.conf -k KEY        # get key KEY from the DHT
327 $ gnunet-statistics -c ~/peer1.conf             # print statistics about current GNUnet state
328 $ gnunet-statistics -c ~/peer1.conf -s dht      # print statistics about DHT service
329 @end example
330
331
332 @subsection Starting Two Peers by Hand
333
334 This section describes how to start two peers on the same machine by hand.
335 The process is rather painful, but the description is somewhat instructive.
336 In practice, you might prefer the automated method
337 (@pxref{Starting Peers Using the Testbed Service}).
338
339 @subsubsection Setup a second peer
340 We will now start a second peer on your machine.
341 For the second peer, you will need to manually create a modified
342 configuration file to avoid conflicts with ports and directories.
343 A peers configuration file is by default located in @file{~/.gnunet/gnunet.conf}.
344 This file is typically very short or even empty as only the differences to the
345 defaults need to be specified.  The defaults are located in
346 many files in the @file{$PREFIX/share/gnunet/config.d} directory.
347
348 To configure the second peer, use the files
349 @file{$PREFIX/share/gnunet/config.d} as a template for your main
350 configuration file:
351 @example
352 $ cat $PREFIX/share/gnunet/config.d/*.conf > peer2.conf
353 @end example
354 Now you have to edit @file{peer2.conf} and change:
355 @itemize
356 @item @code{GNUNET\_TEST\_HOME} under @code{PATHS}
357 @item Every (uncommented) value for ``@code{PORT}'' (add 10000) in any
358 section (the option may be commented out if @code{PORT} is
359 prefixed by "\#", in this case, UNIX domain sockets are used
360 and the PORT option does not need to be touched)
361 @item Every value for ``@code{UNIXPATH}'' in any section (e.g. by adding a "-p2" suffix)
362 @end itemize
363 to a fresh, unique value.  Make sure that the PORT numbers stay below 65536.
364 From now on, whenever you interact with the second peer, you need to specify
365 @command{-c peer2.conf} as an additional command line argument.
366
367 Now, generate the 2nd peer's private key:
368
369 @example
370 $ gnunet-peerinfo -s -c peer2.conf
371 @end example
372
373 This may take a while, generate entropy using your keyboard or mouse
374 as needed.  Also, make sure the output is different from the
375 gnunet-peerinfo output for the first peer (otherwise you made an
376 error in the configuration).
377
378 @subsubsection Start the second peer and connect the peers
379
380 Then, you can start a second peer using:
381 @example
382 $ gnunet-arm -c peer2.conf -s
383 $ gnunet-arm -c peer2.conf -i dht
384 $ ~/gnunet/src/dht/gnunet-dht-put -c peer2.conf -k KEY -d VALUE
385 $ ~/gnunet/src/dht/gnunet-dht-get -c peer2.conf -k KEY
386 @end example
387 If you want the two peers to connect, you have multiple options:
388 @itemize
389 @item UDP neighbour discovery (automatic)
390 @item Setup a bootstrap server
391 @item Connect manually
392 @end itemize
393 To setup peer 1 as bootstrapping server change the configuration of
394 the first one to be a hostlist server by adding the following lines to
395 @file{peer1.conf} to enable bootstrapping server:
396 @example
397 [hostlist]
398 OPTIONS = -p
399 @end example
400
401 Then change @file{peer2.conf} and replace the ``@code{SERVERS}'' line in the ``@code{[hostlist]}'' section with
402 ``@code{http://localhost:8080/}''.  Restart both peers using:
403 @example
404 $ gnunet-arm -c peer1.conf -e           # stop first peer
405 $ gnunet-arm -c peer1.conf -s           # start first peer
406 $ gnunet-arm -c peer2.conf -s           # start second peer
407 @end example
408
409 Note that if you start your peers without changing these settings, they
410 will use the ``global'' hostlist servers of the GNUnet P2P network and
411 likely connect to those peers.  At that point, debugging might become
412 tricky as you're going to be connected to many more peers and would
413 likely observe traffic and behaviors that are not explicitly controlled
414 by you.
415
416 @subsubsection How to connect manually
417
418 If you want to use the @code{peerinfo} tool to connect your peers, you should:
419 @itemize
420 @item Set @code{FORCESTART = NO} in section @code{hostlist} (to not connect to the global GNUnet)
421 @item Start both peers running @command{gnunet-arm -c peer1.conf -s} and @command{gnunet-arm -c peer2.conf -s}
422 @item Get @code{HELLO} message of the first peer running @command{gnunet-peerinfo -c peer1.conf -g}
423 @item Give the output to the second peer by running @command{gnunet-peerinfo -c peer2.conf -p '<output>'}
424 @end itemize
425
426 Check that they are connected using @command{gnunet-core -c peer1.conf},
427 which should give you the other peer's peer identity:
428 @example
429 $ gnunet-core -c peer1.conf
430 Peer `9TVUCS8P5A7ILLBGO6 [...shortened...] 1KNBJ4NGCHP3JPVULDG'
431 @end example
432
433 @subsection Starting Peers Using the Testbed Service
434 @c \label{sec:testbed}
435
436 GNUnet's testbed service is used for testing scenarios where a number of peers
437 are to be started.  The testbed can manage peers on a single host or on multiple
438 hosts in a distributed fashion.  On a single affordable computer, it should be
439 possible to run around tens of peers without drastically increasing the load on the
440 system.
441
442 The testbed service can be access through its API
443 @file{include/gnunet\_testbed\_service.h}.  The API provides many routines for
444 managing a group of peers.  It also provides a helper function
445 @code{GNUNET\_TESTBED\_test\_run()} to quickly setup a minimalistic testing
446 environment on a single host.
447
448 This function takes a configuration file which will be used as a template
449 configuration for the peers.  The testbed takes care of modifying relevant
450 options in the peers' configuration such as @code{SERVICEHOME}, @code{PORT}, @code{UNIXPATH} to
451 unique values so that peers run without running into conflicts.  It also checks
452 and assigns the ports in configurations only if they are free.
453
454 Additionally, the testbed service also reads its options from the same
455 configuration file.  Various available options and details about them can be
456 found in the testbed default configuration file @file{src/testbed/testbed.conf}.
457
458 With the testbed API, a sample test case can be structured as follows:
459 @example
460 @verbatiminclude testbed_test.c
461 @end example
462 The source code for the above listing can be found at
463 @uref{https://gnunet.org/git/gnunet.git/tree/doc/testbed_test.c}
464 or in the @file{doc/} folder of your repository check-out.
465 After installing GNUnet, the above source code can be compiled as:
466 @example
467 $ export CPPFLAGS="-I/path/to/gnunet/headers"
468 $ export LDFLAGS="-L/path/to/gnunet/libraries"
469 $ gcc $CPPFLAGS $LDFLAGS -o testbed-test testbed_test.c  -lgnunettestbed -lgnunetdht -lgnunetutil
470 $ touch template.conf # Generate (empty) configuration
471 $ ./testbed-test  # run it (press CTRL-C to stop)
472 @end example
473 The @code{CPPFLAGS} and @code{LDFLAGS} are necessary if GNUnet is installed
474 into a different directory other than @file{/usr/local}.
475
476 All of testbed API's peer management functions treat management actions as
477 operations and return operation handles.  It is expected that the operations
478 begin immediately, but they may get delayed (to balance out load on the system).
479 The program using the API then has to take care of marking the operation as
480 ``done'' so that its associated resources can be freed immediately and other
481 waiting operations can be executed.  Operations will be canceled if they are
482 marked as ``done'' before their completion.
483
484 An operation is treated as completed when it succeeds or fails.  Completion of
485 an operation is either conveyed as events through @i{controller event callback}
486 or through respective operation completion callbacks.  In functions
487 which support completion notification through both controller event callback and
488 operation completion callback, first the controller event callback will be
489 called.  If the operation is not marked as done in that callback or if the
490 callback is given as NULL when creating the operation, the operation completion
491 callback will be called.  The API documentation shows which event are to be
492 expected in the controller event notifications.  It also documents any
493 exceptional behaviour.
494
495 Once the peers are started, test cases often need to connect some of the peers'
496 services.  Normally, opening a connect to a peer's service requires the peer's
497 configuration.  While using testbed, the testbed automatically generates
498 per-peer configuration.  Accessing those configurations directly through file
499 system is discouraged as their locations are dynamically created and will be
500 different among various runs of testbed.  To make access to these configurations
501 easy, testbed API provides the function
502 @code{GNUNET\_TESTBED\_service\_connect()}.  This function fetches the
503 configuration of a given peer and calls the @i{Connect Adapter}.
504 In the example code, it is the @code{dht\_ca}.  A connect adapter is expected
505 to open the connection to the needed service by using the provided configuration
506 and return the created service connection handle.  Successful connection to the
507 needed service is signaled through @code{service\_connect\_comp\_cb}.
508
509 A dual to connect adapter is the @i{Disconnect Adapter}.  This callback is
510 called after the connect adapter has been called when the operation from
511 @code{GNUNET\_TESTBED\_service\_connect()} is marked as ``done''.  It has to
512 disconnect from the service with the provided service handle (@code{op\_result}).
513
514 Exercise: Find out how many peers you can run on your system.
515
516 Exercise: Find out how to create a 2D torus topology by changing the
517 options in the configuration file. See @uref{https://gnunet.org/supported-topologies}
518 Then use the DHT API to store and retrieve values in the
519 network.
520
521
522 @section Developing Applications
523
524 @subsection gnunet-ext
525 To develop a new peer-to-peer application or to extend GNUnet we provide
526 a template build system for writing GNUnet extensions in C. It can be
527 obtained as follows:
528
529 @example
530 $ git clone https://gnunet.org/git/gnunet-ext
531 $ cd gnunet-ext/
532 $ ./bootstrap
533 $ ./configure --prefix=$PREFIX --with-gnunet=$PREFIX
534 $ make
535 $ make install
536 $ make check
537 @end example
538
539 The GNUnet ext template includes examples and a working buildsystem for a new GNUnet service.
540 A common GNUnet service consists of the following parts which will be discussed in detail in the
541 remainder of this document. The functionality of a GNUnet service is implemented in:
542
543 @itemize
544 @item the GNUnet service (gnunet-ext/src/ext/gnunet-service-ext.c)
545 @item the client API (gnunet-ext/src/ext/ext_api.c)
546 @item the client application using the service API (gnunet-ext/src/ext/gnunet-ext.c)
547 @end itemize
548
549 The interfaces for these entities are defined in:
550 @itemize
551 @item client API interface (gnunet-ext/src/ext/ext.h)
552 @item the service interface (gnunet-ext/src/include/gnunet_service_SERVICE.h)
553 @item the P2P protocol (gnunet-ext/src/include/gnunet_protocols_ext.h)
554 @end itemize
555
556
557 In addition the ext systems provides:
558 @itemize
559 @item a test testing the API (gnunet-ext/src/ext/test_ext_api.c)
560 @item a configuration template for the service (gnunet-ext/src/ext/ext.conf.in)
561 @end itemize
562
563 @subsection Adapting the Template
564
565 The first step for writing any extension with a new service is to
566 ensure that the @file{ext.conf.in} file contains entries for the
567 @code{UNIXPATH}, @code{PORT} and @code{BINARY} for the service in a section named after
568 the service.
569
570 If you want to adapt the template rename the @file{ext.conf.in} to match your
571 services name, you have to modify the @code{AC\_OUTPUT} section in @file{configure.ac}
572 in the @file{gnunet-ext} root.
573
574 @section Writing a Client Application
575
576 When writing any client application (for example, a command-line
577 tool), the basic structure is to start with the @code{GNUNET\_PROGRAM\_run}
578 function.  This function will parse command-line options, setup the scheduler
579 and then invoke the @code{run} function (with the remaining non-option arguments)
580 and a handle to the parsed configuration (and the configuration file name that was
581 used, which is typically not needed):
582 @example
583 @verbatiminclude tutorial-examples/001.c
584 @end example
585
586 @subsection Handling command-line options
587
588 Options can then be added easily by adding global variables and
589 expanding the @code{options} array.  For example, the following would
590 add a string-option and a binary flag (defaulting to @code{NULL} and
591 @code{GNUNET\_NO} respectively):
592 @example
593 @verbatiminclude tutorial-examples/002.c
594 @end example
595
596 Issues such as displaying some helpful text describing options using
597 the @code{--help} argument and error handling are taken care of when
598 using this approach.  Other @code{GNUNET\_GETOPT\_}-functions can be used
599 to obtain integer value options, increment counters, etc.  You can
600 even write custom option parsers for special circumstances not covered
601 by the available handlers. To check if an argument was specified by the
602 user you initialize the variable with a specific value (e.g. NULL for
603 a string and GNUNET\_SYSERR for a integer) and check after parsing
604 happened if the values were modified.
605
606 Inside the @code{run} method, the program would perform the
607 application-specific logic, which typically involves initializing and
608 using some client library to interact with the service.  The client
609 library is supposed to implement the IPC whereas the service provides
610 more persistent P2P functions.
611
612 Exercise: Add a few command-line options and print them inside
613 of @code{run}.  What happens if the user gives invalid arguments?
614
615 @subsection Writing a Client Library
616
617 The first and most important step in writing a client library is to
618 decide on an API for the library.  Typical API calls include
619 connecting to the service, performing application-specific requests
620 and cleaning up.  Many examples for such service APIs can be found
621 in the @file{gnunet/src/include/gnunet\_*\_service.h} files.
622
623 Then, a client-service protocol needs to be designed.  This typically
624 involves defining various message formats in a header that will be
625 included by both the service and the client library (but is otherwise
626 not shared and hence located within the service's directory and not
627 installed by @command{make install}).  Each message must start with a
628 @code{struct GNUNET\_MessageHeader} and must be shorter than 64k.  By
629 convention, all fields in IPC (and P2P) messages must be in big-endian
630 format (and thus should be read using @code{ntohl} and similar
631 functions and written using @code{htonl} and similar functions).
632 Unique message types must be defined for each message struct in the
633 @file{gnunet\_protocols.h} header (or an extension-specific include
634 file).
635
636 @subsubsection Connecting to the Service
637
638 Before a client library can implement the application-specific protocol
639 with the service, a connection must be created:
640 @example
641 @verbatiminclude tutorial-examples/003.c
642 @end example
643
644 As a result a @code{GNUNET\_MQ\_Handle} is returned
645 which can to used henceforth to transmit messages to the service.
646 The complete MQ API can be found in @file{gnunet\_mq\_lib.h}.
647 The @code{hanlders} array in the example above is incomplete.
648 Here is where you will define which messages you expect to
649 receive from the service, and which functions handle them.
650 The @code{error\_cb} is a function that is to be called whenever
651 there are errors communicating with the service.
652
653 @subsubsection Sending messages
654
655 In GNUnet, messages are always sent beginning with a @code{struct GNUNET\_MessageHeader}
656 in big endian format. This header defines the size and the type of the
657 message, the payload follows after this header.
658 @example
659 @verbatiminclude tutorial-examples/004.c
660 @end example
661
662 Existing message types are defined in @file{gnunet\_protocols.h}.
663 A common way to create a message is with an envelope:
664 @example
665 @verbatiminclude tutorial-examples/005.c
666 @end example
667
668 Exercise: Define a message struct that includes a 32-bit
669 unsigned integer in addition to the standard GNUnet MessageHeader.
670 Add a C struct and define a fresh protocol number for your message.
671 Protocol numbers in gnunet-ext are defined in @file{gnunet-ext/src/include/gnunet_protocols_ext.h}
672
673 Exercise: Find out how you can determine the number of messages in a message queue.
674
675 Exercise: Find out how you can determine when a message you have queued was actually transmitted.
676
677 Exercise: Define a helper function to transmit a 32-bit
678 unsigned integer (as payload) to a service using some given client
679 handle.
680
681
682 @subsubsection Receiving Replies from the Service
683
684 Clients can receive messages from the service using the handlers
685 specified in the @code{handlers} array we specified when connecting
686 to the service.  Entries in the the array are usually created using
687 one of two macros, depending on whether the message is fixed size
688 or variable size.  Variable size messages are managed using two
689 callbacks, one to check that the message is well-formed, the other
690 to actually process the message.  Fixed size messages are fully
691 checked by the MQ-logic, and thus only need to provide the handler
692 to process the message.  Note that the prefixes @code{check\_}
693 and @code{handle\_} are mandatory.
694 @example
695 @verbatiminclude tutorial-examples/006.c
696 @end example
697
698 Exercise: Expand your helper function to receive a response message
699 (for example, containing just the @code{struct GNUnet MessageHeader}
700 without any payload).  Upon receiving the service's response, you
701 should call a callback provided to your helper function's API.
702
703 Exercise: Figure out where you can pass values to the closures (@code{cls}).
704
705
706 @subsection Writing a user interface
707
708 Given a client library, all it takes to access a service now is to
709 combine calls to the client library with parsing command-line
710 options.
711
712 Exercise: Call your client API from your @code{run()} method in your
713 client application to send a request to the service.  For example,
714 send a 32-bit integer value based on a number given at the
715 command-line to the service.
716
717 @section Writing a Service
718
719 Before you can test the client you've written so far, you'll need to also
720 implement the corresponding service.
721
722 @subsection Code Placement
723
724 New services are placed in their own subdirectory under @file{gnunet/src}.
725 This subdirectory should contain the API implementation file @file{SERVICE\_api.c},
726 the description of the client-service protocol @file{SERVICE.h} and P2P protocol
727 @file{SERVICE\_protocol.h}, the implementation of the service itself
728 @file{gnunet-service-SERVICE.h} and several files for tests, including test code
729 and configuration files.
730
731 @subsection Starting a Service
732
733 The key API definition for creating a service is the @code{GNUNET\_SERVICE\_MAIN} macro:
734 @example
735 @verbatiminclude tutorial-examples/007.c
736 @end example
737
738 In addition to the service name and flags, the macro takes three
739 functions, typically called @code{run}, @code{client\_connect\_cb} and
740 @code{client\_disconnect\_cb} as well as an array of message handlers
741 that will be called for incoming messages from clients.
742
743 A minimal version of the three central service funtions would look
744 like this:
745 @example
746 @verbatiminclude tutorial-examples/008.c
747 @end example
748
749 Exercise: Write a stub service that processes no messages at all
750 in your code.  Create a default configuration for it, integrate it
751 with the build system and start the service from
752 @command{gnunet-service-arm} using @command{gnunet-arm -i NAME}.
753
754 Exercise: Figure out how to set the closure (@code{cls}) for handlers
755 of a service.
756
757 Exercise: Figure out how to send messages from the service back to the
758 client.
759
760 Each handler function in the service @b{must} eventually (possibly in some
761 asynchronous continuation) call @code{GNUNET\_SERVICE\_client\_continue()}.
762 Only after this call additional messages from the same client may
763 be processed. This way, the service can throttle processing messages
764 from the same client.
765
766 Exercise: Change the service to ``handle'' the message from your
767 client (for now, by printing a message).  What happens if you
768 forget to call @code{GNUNET\_SERVICE\_client\_continue()}?
769
770
771 @section Interacting directly with other Peers using the CORE Service
772
773 FIXME: This section still needs to be updated to the lastest API!
774
775 One of the most important services in GNUnet is the @code{CORE} service
776 managing connections between peers and handling encryption between peers.
777
778 One of the first things any service that extends the P2P protocol typically does
779 is connect to the @code{CORE} service using:
780 @example
781 @verbatiminclude tutorial-examples/009.c
782 @end example
783
784 @subsection New P2P connections
785
786 Before any traffic with a different peer can be exchanged, the peer must be
787 known to the service. This is notified by the @code{CORE} @code{connects} callback,
788 which communicates the identity of the new peer to the service:
789 @example
790 @verbatiminclude tutorial-examples/010.c
791 @end example
792
793 Note that whatever you return from @code{connects} is given as the
794 @i{cls} argument to the message handlers for messages from
795 the respective peer.
796
797 Exercise: Create a service that connects to the @code{CORE}.  Then
798 start (and connect) two peers and print a message once your connect
799 callback is invoked.
800
801 @subsection Receiving P2P Messages
802
803 To receive messages from @code{CORE}, you pass the desired
804 @i{handlers} to the @code{GNUNET\_CORE\_connect()} function,
805 just as we showed for services.
806
807 It is your responsibility to process messages fast enough or
808 to implement flow control. If an application does not process
809 CORE messages fast enough, CORE will randomly drop messages
810 to not keep a very long queue in memory.
811
812 Exercise: Start one peer with a new service that has a message
813 handler and start a second peer that only has your ``old'' service
814 without message handlers.  Which ``connect'' handlers are invoked when
815 the two peers are connected?  Why?
816
817
818 @subsection Sending P2P Messages
819
820 You can transmit messages to other peers using the @i{mq} you were
821 given during the @code{connect} callback.  Note that the @i{mq}
822 automatically is released upon @code{disconnect} and that you must
823 not use it afterwards.
824
825 It is your responsibility to not over-fill the message queue, GNUnet
826 will send the messages roughly in the order given as soon as possible.
827
828 Exercise: Write a service that upon connect sends messages as
829 fast as possible to the other peer (the other peer should run a
830 service that ``processes'' those messages).  How fast is the
831 transmission?  Count using the STATISTICS service on both ends.  Are
832 messages lost? How can you transmit messages faster?  What happens if
833 you stop the peer that is receiving your messages?
834
835
836 @subsection End of P2P connections
837
838 If a message handler returns @code{GNUNET\_SYSERR}, the remote peer shuts down or
839 there is an unrecoverable network disconnection, CORE notifies the service that
840 the peer disconnected. After this notification no more messages will be received
841 from the peer and the service is no longer allowed to send messages to the peer.
842 The disconnect callback looks like the following:
843 @example
844 @verbatiminclude tutorial-examples/011.c
845 @end example
846
847 Exercise: Fix your service to handle peer disconnects.
848
849 @section Storing peer-specific data using the PEERSTORE service
850
851 GNUnet's PEERSTORE service offers a persistorage for arbitrary peer-specific data.
852 Other GNUnet services can use the PEERSTORE to store, retrieve and monitor data records.
853 Each data record stored with PEERSTORE contains the following fields:
854
855 @itemize
856 @item subsystem: Name of the subsystem responsible for the record.
857 @item peerid: Identity of the peer this record is related to.
858 @item key: a key string identifying the record.
859 @item value: binary record value.
860 @item expiry: record expiry date.
861 @end itemize
862
863 The first step is to start a connection to the PEERSTORE service:
864 @example
865 @verbatiminclude tutorial-examples/012.c
866 @end example
867
868 The service handle @code{peerstore_handle} will be needed for all subsequent
869 PEERSTORE operations.
870
871 @subsection Storing records
872
873 To store a new record, use the following function:
874 @example
875 @verbatiminclude tutorial-examples/013.c
876 @end example
877
878 The @code{options} parameter can either be @code{GNUNET_PEERSTORE_STOREOPTION_MULTIPLE}
879 which means that multiple values can be stored under the same key combination (subsystem, peerid, key),
880 or @code{GNUNET_PEERSTORE_STOREOPTION_REPLACE} which means that PEERSTORE will replace any
881 existing values under the given key combination (subsystem, peerid, key) with the new given value.
882
883 The continuation function @code{cont} will be called after the store request is successfully
884 sent to the PEERSTORE service. This does not guarantee that the record is successfully stored, only
885 that it was received by the service.
886
887 The @code{GNUNET_PEERSTORE_store} function returns a handle to the store operation. This handle
888 can be used to cancel the store operation only before the continuation function is called:
889 @example
890 void
891 GNUNET_PEERSTORE_store_cancel (struct GNUNET_PEERSTORE_StoreContext *sc);
892 @end example
893
894 @subsection Retrieving records
895
896 To retrieve stored records, use the following function:
897 @example
898 @verbatiminclude tutorial-examples/014.c
899 @end example
900
901 The values of @code{peer} and @code{key} can be @code{NULL}. This allows the
902 iteration over values stored under any of the following key combinations:
903 @itemize
904 @item (subsystem)
905 @item (subsystem, peerid)
906 @item (subsystem, key)
907 @item (subsystem, peerid, key)
908 @end itemize
909
910 The @code{callback} function will be called once with each retrieved record and once
911 more with a @code{NULL} record to signal the end of results.
912
913 The @code{GNUNET_PEERSTORE_iterate} function returns a handle to the iterate operation. This
914 handle can be used to cancel the iterate operation only before the callback function is called with
915 a @code{NULL} record.
916
917 @subsection Monitoring records
918
919 PEERSTORE offers the functionality of monitoring for new records stored under a specific key
920 combination (subsystem, peerid, key). To start the monitoring, use the following function:
921 @example
922 @verbatiminclude tutorial-examples/015.c
923 @end example
924
925 Whenever a new record is stored under the given key combination, the @code{callback} function
926 will be called with this new record. This will continue until the connection to the PEERSTORE service
927 is broken or the watch operation is canceled:
928 @example
929 @verbatiminclude tutorial-examples/016.c
930 @end example
931
932 @subsection Disconnecting from PEERSTORE
933
934 When the connection to the PEERSTORE service is no longer needed, disconnect using the following
935 function:
936 @example
937 @verbatiminclude tutorial-examples/017.c
938 @end example
939
940 If the @code{sync_first} flag is set to @code{GNUNET_YES}, the API will delay the
941 disconnection until all store requests are received by the PEERSTORE service. Otherwise,
942 it will disconnect immediately.
943
944
945 @section Using the DHT
946
947 The DHT allows to store data so other peers in the P2P network can
948 access it and retrieve data stored by any peers in the network.
949 This section will explain how to use the DHT. Of course, the first
950 thing to do is to connect to the DHT service:
951 @example
952 @verbatiminclude tutorial-examples/018.c
953 @end example
954
955 The second parameter indicates how many requests in parallel to expect.
956 It is not a hard limit, but a good approximation will make the DHT more
957 efficient.
958
959 @subsection Storing data in the DHT
960 Since the DHT is a dynamic environment (peers join and leave frequently)
961 the data that we put in the DHT does not stay there indefinitely. It is
962 important to ``refresh'' the data periodically by simply storing it again,
963 in order to make sure other peers can access it.
964
965 The put API call offers a callback to signal that the PUT request has been
966 sent. This does not guarantee that the data is accessible to others peers,
967 or even that is has been stored, only that the service has requested to
968 a neighboring peer the retransmission of the PUT request towards its final
969 destination. Currently there is no feedback about whether or not the data
970 has been sucessfully stored or where it has been stored. In order to improve
971 the availablilty of the data and to compensate for possible errors, peers leaving
972 and other unfavorable events, just make several PUT requests!
973 @example
974 @verbatiminclude tutorial-examples/019.c
975 @end example
976
977 Exercise: Store a value in the DHT periodically to make sure it is available
978 over time. You might consider using the function @code{GNUNET\_SCHEDULER\_add\_delayed}
979 and call @code{GNUNET\_DHT\_put} from inside a helper function.
980
981
982 @subsection Obtaining data from the DHT
983 As we saw in the previous example, the DHT works in an asynchronous mode.
984 Each request to the DHT is executed ``in the background'' and the API
985 calls return immediately. In order to receive results from the DHT, the
986 API provides a callback. Once started, the request runs in the service,
987 the service will try to get as many results as possible (filtering out
988 duplicates) until the timeout expires or we explicitly stop the request.
989 It is possible to give a ``forever'' timeout with
990 @code{GNUNET\_TIME\_UNIT\_FOREVER\_REL}.
991
992 If we give a route option @code{GNUNET\_DHT\_RO\_RECORD\_ROUTE} the callback
993 will get a list of all the peers the data has travelled, both on the PUT
994 path and on the GET path.
995 @example
996 @verbatiminclude tutorial-examples/020.c
997 @end example
998
999 Exercise: Store a value in the DHT and after a while retrieve it. Show the IDs of all
1000 the peers the requests have gone through. In order to convert a peer ID to a string, use
1001 the function @code{GNUNET\_i2s}. Pay attention to the route option parameters in both calls!
1002
1003 @subsection Implementing a block plugin
1004
1005 In order to store data in the DHT, it is necessary to provide a block
1006 plugin.  The DHT uses the block plugin to ensure that only well-formed
1007 requests and replies are transmitted over the network.
1008
1009 The block plugin should be put in a file @file{plugin\_block\_SERVICE.c}
1010 in the service's respective directory. The
1011 mandatory functions that need to be implemented for a block plugin are
1012 described in the following sections.
1013
1014 @subsubsection Validating requests and replies
1015
1016 The evaluate function should validate a reply or a request. It returns
1017 a @code{GNUNET\_BLOCK\_EvaluationResult}, which is an enumeration. All
1018 possible answers are in @file{gnunet\_block\_lib.h}.  The function will
1019 be called with a @code{reply\_block} argument of @code{NULL} for
1020 requests.  Note that depending on how @code{evaluate} is called, only
1021 some of the possible return values are valid.  The specific meaning of
1022 the @code{xquery} argument is application-specific.  Applications that
1023 do not use an extended query should check that the @code{xquery\_size}
1024 is zero.  The block group is typically used to filter duplicate
1025 replies.
1026 @example
1027 @verbatiminclude tutorial-examples/021.c
1028 @end example
1029
1030 Note that it is mandatory to detect duplicate replies in this function
1031 and return the respective status code.  Duplicate detection is
1032 typically done using the Bloom filter block group provided by
1033 @file{libgnunetblockgroup.so}.  Failure to do so may cause replies to
1034 circle in the network.
1035
1036 @subsubsection Deriving a key from a reply
1037
1038 The DHT can operate more efficiently if it is possible to derive a key
1039 from the value of the corresponding block.  The @code{get\_key}
1040 function is used to obtain the key of a block --- for example, by
1041 means of hashing.  If deriving the key is not possible, the function
1042 should simply return @code{GNUNET\_SYSERR} (the DHT will still work
1043 just fine with such blocks).
1044 @example
1045 @verbatiminclude tutorial-examples/022.c
1046 @end example
1047
1048 @subsubsection Initialization of the plugin
1049
1050 The plugin is realized as a shared C library.  The library must export
1051 an initialization function which should initialize the plugin.  The
1052 initialization function specifies what block types the plugin cares
1053 about and returns a struct with the functions that are to be used for
1054 validation and obtaining keys (the ones just defined above).
1055 @example
1056 @verbatiminclude tutorial-examples/023.c
1057 @end example
1058
1059 @subsubsection Shutdown of the plugin
1060
1061 Following GNUnet's general plugin API concept, the plugin must
1062 export a second function for cleaning up.  It usually does very
1063 little.
1064 @example
1065 @verbatiminclude tutorial-examples/024.c
1066 @end example
1067
1068 @subsubsection Integration of the plugin with the build system
1069
1070 In order to compile the plugin, the @file{Makefile.am} file for the
1071 service SERVICE should contain a rule similar to this:
1072 @c* Actually this is a Makefile not C. But the whole structure of examples
1073 @c* must be improved.
1074 @example
1075 @verbatiminclude tutorial-examples/025.c
1076 @end example
1077
1078 Exercise: Write a block plugin that accepts all queries
1079 and all replies but prints information about queries and replies
1080 when the respective validation hooks are called.
1081
1082 @subsection Monitoring the DHT
1083 It is possible to monitor the functioning of the local DHT service. When monitoring
1084 the DHT, the service will alert the monitoring program of any events,
1085 both started locally or received for routing from another peer. The are three different
1086 types of events possible: a GET request, a PUT request or a response (a reply to
1087 a GET).
1088
1089 Since the different events have different associated data, the API gets 3
1090 different callbacks (one for each message type) and optional type and key parameters,
1091 to allow for filtering of messages. When an event happens, the appropiate callback
1092 is called with all the information about the event.
1093 @example
1094 @verbatiminclude tutorial-examples/026.c
1095 @end example
1096
1097 @section Debugging with gnunet-arm
1098
1099 Even if services are managed by @command{gnunet-arm}, you can start them with
1100 @command{gdb} or @command{valgrind}.  For example, you could add the following lines
1101 to your configuration file to start the DHT service in a @command{gdb} session in a
1102 fresh @command{xterm}:
1103
1104 @example
1105 [dht]
1106 PREFIX=xterm -e gdb --args
1107 @end example
1108
1109 Alternatively, you can stop a service that was started via ARM and run it manually:
1110
1111 @example
1112 $ gnunet-arm -k dht
1113 $ gdb --args gnunet-service-dht -L DEBUG
1114 $ valgrind gnunet-service-dht -L DEBUG
1115 @end example
1116
1117 Assuming other services are well-written, they will automatically re-integrate the
1118 restarted service with the peer.
1119
1120 GNUnet provides a powerful logging mechanism providing log levels @code{ERROR},
1121 @code{WARNING}, @code{INFO} and @code{DEBUG}. The current log level is
1122 configured using the @code{$GNUNET_FORCE_LOG} environmental variable.
1123 The @code{DEBUG} level is only available if @command{--enable-logging=verbose} was used when
1124 running @command{configure}. More details about logging can be found under
1125 @uref{https://gnunet.org/logging}.
1126
1127 You should also probably enable the creation of core files, by setting
1128 @code{ulimit}, and echo'ing @code{1} into @file{/proc/sys/kernel/core\_uses\_pid}.
1129 Then you can investigate the core dumps with @command{gdb}, which is often
1130 the fastest method to find simple errors.
1131
1132 Exercise: Add a memory leak to your service and obtain a trace
1133 pointing to the leak using @command{valgrind} while running the service
1134 from @command{gnunet-service-arm}.
1135
1136 @bye