Merge branch 'master' of git+ssh://gnunet.org/gnunet
[oweals/gnunet.git] / doc / handbook / chapters / developer.texi
1 @c ***********************************************************************
2 @node GNUnet Developer Handbook
3 @chapter GNUnet Developer Handbook
4
5 This book is intended to be an introduction for programmers that want to
6 extend the GNUnet framework. GNUnet is more than a simple peer-to-peer
7 application.
8
9 For developers, GNUnet is:
10
11 @itemize @bullet
12 @item developed by a community that believes in the GNU philosophy
13 @item Free Software (Free as in Freedom), licensed under the
14 GNU Affero General Public License
15 (@uref{https://www.gnu.org/licenses/licenses.html#AGPL})
16 @item A set of standards, including coding conventions and
17 architectural rules
18 @item A set of layered protocols, both specifying the communication
19 between peers as well as the communication between components
20 of a single peer
21 @item A set of libraries with well-defined APIs suitable for
22 writing extensions
23 @end itemize
24
25 In particular, the architecture specifies that a peer consists of many
26 processes communicating via protocols. Processes can be written in almost
27 any language.
28 @code{C}, @code{Java} and @code{Guile} APIs exist for accessing existing
29 services and for writing extensions.
30 It is possible to write extensions in other languages by
31 implementing the necessary IPC protocols.
32
33 GNUnet can be extended and improved along many possible dimensions, and
34 anyone interested in Free Software and Freedom-enhancing Networking is
35 welcome to join the effort. This Developer Handbook attempts to provide
36 an initial introduction to some of the key design choices and central
37 components of the system.
38 This part of the GNUNet documentation is far from complete,
39 and we welcome informed contributions, be it in the form of
40 new chapters, sections or insightful comments.
41
42 @menu
43 * Developer Introduction::
44 * Internal dependencies::
45 * Code overview::
46 * System Architecture::
47 * Subsystem stability::
48 * Naming conventions and coding style guide::
49 * Build-system::
50 * Developing extensions for GNUnet using the gnunet-ext template::
51 * Writing testcases::
52 * Building GNUnet and its dependencies::
53 * TESTING library::
54 * Performance regression analysis with Gauger::
55 * TESTBED Subsystem::
56 * libgnunetutil::
57 * Automatic Restart Manager (ARM)::
58 * TRANSPORT Subsystem::
59 * NAT library::
60 * Distance-Vector plugin::
61 * SMTP plugin::
62 * Bluetooth plugin::
63 * WLAN plugin::
64 * ATS Subsystem::
65 * CORE Subsystem::
66 * CADET Subsystem::
67 * NSE Subsystem::
68 * HOSTLIST Subsystem::
69 * IDENTITY Subsystem::
70 * NAMESTORE Subsystem::
71 * PEERINFO Subsystem::
72 * PEERSTORE Subsystem::
73 * SET Subsystem::
74 * STATISTICS Subsystem::
75 * Distributed Hash Table (DHT)::
76 * GNU Name System (GNS)::
77 * GNS Namecache::
78 * REVOCATION Subsystem::
79 * File-sharing (FS) Subsystem::
80 * REGEX Subsystem::
81 * REST Subsystem::
82 @end menu
83
84 @node Developer Introduction
85 @section Developer Introduction
86
87 This Developer Handbook is intended as first introduction to GNUnet for
88 new developers that want to extend the GNUnet framework. After the
89 introduction, each of the GNUnet subsystems (directories in the
90 @file{src/} tree) is (supposed to be) covered in its own chapter. In
91 addition to this documentation, GNUnet developers should be aware of the
92 services available on the GNUnet server to them.
93
94 New developers can have a look a the GNUnet tutorials for C and java
95 available in the @file{src/} directory of the repository or under the
96 following links:
97
98 @c ** FIXME: Link to files in source, not online.
99 @c ** FIXME: Where is the Java tutorial?
100 @itemize @bullet
101 @item @xref{Top, Introduction,, gnunet-c-tutorial, The GNUnet C Tutorial}.
102 @item @uref{https://tutorial.gnunet.org/, GNUnet C tutorial}
103 @item GNUnet Java tutorial
104 @end itemize
105
106 In addition to the GNUnet Reference Documentation you are reading,
107 the GNUnet server at @uref{https://gnunet.org} contains
108 various resources for GNUnet developers and those
109 who aspire to become regular contributors.
110 They are all conveniently reachable via the "Developer"
111 entry in the navigation menu. Some additional tools (such as static
112 analysis reports) require a special developer access to perform certain
113 operations. If you want (or require) access, you should contact
114 @uref{http://grothoff.org/christian/, Christian Grothoff},
115 GNUnet's maintainer.
116
117 @c FIXME: A good part of this belongs on the website or should be
118 @c extended in subsections explaining usage of this. A simple list
119 @c is just taking space people have to read.
120 The public subsystems on the GNUnet server that help developers are:
121
122 @itemize @bullet
123
124 @item The version control system (git) keeps our code and enables
125 distributed development.
126 It is publicly accessible at @uref{https://git.gnunet.org/}.
127 Only developers with write access can commit code, everyone else is
128 encouraged to submit patches to the GNUnet-developers mailinglist:
129 @uref{https://lists.gnu.org/mailman/listinfo/gnunet-developers, https://lists.gnu.org/mailman/listinfo/gnunet-developers}
130
131 @item The bugtracking system (Mantis).
132 We use it to track feature requests, open bug reports and their
133 resolutions.
134 It can be accessed at
135 @uref{https://bugs.gnunet.org/, https://bugs.gnunet.org/}.
136 Anyone can report bugs.
137
138 @item Our site installation of the
139 Continuous Integration (CI) system @code{Buildbot} is used
140 to check GNUnet builds automatically on a range of platforms.
141 The web interface of this CI is exposed at
142 @uref{https://old.gnunet.org/buildbot/, https://old.gnunet.org/buildbot/}.
143 Builds are triggered automatically 30 minutes after the last commit to
144 our repository was made.
145
146 @item The current quality of our automated test suite is assessed using
147 Code coverage analysis. This analysis is run daily; however the webpage
148 is only updated if all automated tests pass at that time. Testcases that
149 improve our code coverage are always welcome.
150
151 @item We try to automatically find bugs using a static analysis scan.
152 This scan is run daily; however the webpage is only updated if all
153 automated tests pass at the time. Note that not everything that is
154 flagged by the analysis is a bug, sometimes even good code can be marked
155 as possibly problematic. Nevertheless, developers are encouraged to at
156 least be aware of all issues in their code that are listed.
157
158 @item We use Gauger for automatic performance regression visualization.
159 @c FIXME: LINK!
160 Details on how to use Gauger are here.
161
162 @item We use @uref{http://junit.org/, junit} to automatically test
163 @command{gnunet-java}.
164 Automatically generated, current reports on the test suite are here.
165 @c FIXME: Likewise.
166
167 @item We use Cobertura to generate test coverage reports for gnunet-java.
168 Current reports on test coverage are here.
169 @c FIXME: Likewise.
170
171 @end itemize
172
173
174
175 @c ***********************************************************************
176 @menu
177 * Project overview::
178 @end menu
179
180 @node Project overview
181 @subsection Project overview
182
183 The GNUnet project consists at this point of several sub-projects. This
184 section is supposed to give an initial overview about the various
185 sub-projects. Note that this description also lists projects that are far
186 from complete, including even those that have literally not a single line
187 of code in them yet.
188
189 GNUnet sub-projects in order of likely relevance are currently:
190
191 @table @asis
192
193 @item @command{gnunet}
194 Core of the P2P framework, including file-sharing, VPN and
195 chat applications; this is what the Developer Handbook covers mostly
196 @item @command{gnunet-gtk}
197 Gtk+-based user interfaces, including:
198
199 @itemize @bullet
200 @item @command{gnunet-fs-gtk} (file-sharing),
201 @item @command{gnunet-statistics-gtk} (statistics over time),
202 @item @command{gnunet-peerinfo-gtk}
203 (information about current connections and known peers),
204 @item @command{gnunet-namestore-gtk} (GNS record editor),
205 @item @command{gnunet-conversation-gtk} (voice chat GUI) and
206 @item @command{gnunet-setup} (setup tool for "everything")
207 @end itemize
208
209 @item @command{gnunet-fuse}
210 Mounting directories shared via GNUnet's file-sharing
211 on GNU/Linux distributions
212 @item @command{gnunet-update}
213 Installation and update tool
214 @item @command{gnunet-ext}
215 Template for starting 'external' GNUnet projects
216 @item @command{gnunet-java}
217 Java APIs for writing GNUnet services and applications
218 @item @command{gnunet-java-ext}
219 @item @command{eclectic}
220 Code to run GNUnet nodes on testbeds for research, development,
221 testing and evaluation
222 @c ** FIXME: Solve the status and location of gnunet-qt
223 @item @command{gnunet-qt}
224 Qt-based GNUnet GUI (is it deprecated?)
225 @item @command{gnunet-cocoa}
226 cocoa-based GNUnet GUI (is it deprecated?)
227 @item @command{gnunet-guile}
228 Guile bindings for GNUnet
229 @item @command{gnunet-python}
230 Python bindings for GNUnet
231
232 @end table
233
234 We are also working on various supporting libraries and tools:
235 @c ** FIXME: What about gauger, and what about libmwmodem?
236
237 @table @asis
238 @item @command{libextractor}
239 GNU libextractor (meta data extraction)
240 @item @command{libmicrohttpd}
241 GNU libmicrohttpd (embedded HTTP(S) server library)
242 @item @command{gauger}
243 Tool for performance regression analysis
244 @item @command{monkey}
245 Tool for automated debugging of distributed systems
246 @item @command{libmwmodem}
247 Library for accessing satellite connection quality reports
248 @item @command{libgnurl}
249 gnURL (feature-restricted variant of cURL/libcurl)
250 @item @command{www}
251 work in progress of the new gnunet.org website (Jinja2 framework based to
252 replace our current Drupal website)
253 @item @command{bibliography}
254 Our collected bibliography, papers, references, and so forth
255 @item @command{gnunet-videos-}
256 Videos about and around gnunet activities
257 @end table
258
259 Finally, there are various external projects (see links for a list of
260 those that have a public website) which build on top of the GNUnet
261 framework.
262
263 @c ***********************************************************************
264 @node Internal dependencies
265 @section Internal dependencies
266
267 This section tries to give an overview of what processes a typical GNUnet
268 peer running a particular application would consist of. All of the
269 processes listed here should be automatically started by
270 @command{gnunet-arm -s}.
271 The list is given as a rough first guide to users for failure diagnostics.
272 Ideally, end-users should never have to worry about these internal
273 dependencies.
274
275 In terms of internal dependencies, a minimum file-sharing system consists
276 of the following GNUnet processes (in order of dependency):
277
278 @itemize @bullet
279 @item gnunet-service-arm
280 @item gnunet-service-resolver (required by all)
281 @item gnunet-service-statistics (required by all)
282 @item gnunet-service-peerinfo
283 @item gnunet-service-transport (requires peerinfo)
284 @item gnunet-service-core (requires transport)
285 @item gnunet-daemon-hostlist (requires core)
286 @item gnunet-daemon-topology (requires hostlist, peerinfo)
287 @item gnunet-service-datastore
288 @item gnunet-service-dht (requires core)
289 @item gnunet-service-identity
290 @item gnunet-service-fs (requires identity, mesh, dht, datastore, core)
291 @end itemize
292
293 @noindent
294 A minimum VPN system consists of the following GNUnet processes (in
295 order of dependency):
296
297 @itemize @bullet
298 @item gnunet-service-arm
299 @item gnunet-service-resolver (required by all)
300 @item gnunet-service-statistics (required by all)
301 @item gnunet-service-peerinfo
302 @item gnunet-service-transport (requires peerinfo)
303 @item gnunet-service-core (requires transport)
304 @item gnunet-daemon-hostlist (requires core)
305 @item gnunet-service-dht (requires core)
306 @item gnunet-service-mesh (requires dht, core)
307 @item gnunet-service-dns (requires dht)
308 @item gnunet-service-regex (requires dht)
309 @item gnunet-service-vpn (requires regex, dns, mesh, dht)
310 @end itemize
311
312 @noindent
313 A minimum GNS system consists of the following GNUnet processes (in
314 order of dependency):
315
316 @itemize @bullet
317 @item gnunet-service-arm
318 @item gnunet-service-resolver (required by all)
319 @item gnunet-service-statistics (required by all)
320 @item gnunet-service-peerinfo
321 @item gnunet-service-transport (requires peerinfo)
322 @item gnunet-service-core (requires transport)
323 @item gnunet-daemon-hostlist (requires core)
324 @item gnunet-service-dht (requires core)
325 @item gnunet-service-mesh (requires dht, core)
326 @item gnunet-service-dns (requires dht)
327 @item gnunet-service-regex (requires dht)
328 @item gnunet-service-vpn (requires regex, dns, mesh, dht)
329 @item gnunet-service-identity
330 @item gnunet-service-namestore (requires identity)
331 @item gnunet-service-gns (requires vpn, dns, dht, namestore, identity)
332 @end itemize
333
334 @c ***********************************************************************
335 @node Code overview
336 @section Code overview
337
338 This section gives a brief overview of the GNUnet source code.
339 Specifically, we sketch the function of each of the subdirectories in
340 the @file{gnunet/src/} directory. The order given is roughly bottom-up
341 (in terms of the layers of the system).
342
343 @table @asis
344 @item @file{util/} --- libgnunetutil
345 Library with general utility functions, all
346 GNUnet binaries link against this library. Anything from memory
347 allocation and data structures to cryptography and inter-process
348 communication. The goal is to provide an OS-independent interface and
349 more 'secure' or convenient implementations of commonly used primitives.
350 The API is spread over more than a dozen headers, developers should study
351 those closely to avoid duplicating existing functions.
352 @pxref{libgnunetutil}.
353 @item @file{hello/} --- libgnunethello
354 HELLO messages are used to
355 describe under which addresses a peer can be reached (for example,
356 protocol, IP, port). This library manages parsing and generating of HELLO
357 messages.
358 @item @file{block/} --- libgnunetblock
359 The DHT and other components of GNUnet
360 store information in units called 'blocks'. Each block has a type and the
361 type defines a particular format and how that binary format is to be
362 linked to a hash code (the key for the DHT and for databases). The block
363 library is a wrapper around block plugins which provide the necessary
364 functions for each block type.
365 @item @file{statistics/} --- statistics service
366 The statistics service enables associating
367 values (of type uint64_t) with a component name and a string. The main
368 uses is debugging (counting events), performance tracking and user
369 entertainment (what did my peer do today?).
370 @item @file{arm/} --- Automatic Restart Manager (ARM)
371 The automatic-restart-manager (ARM) service
372 is the GNUnet master service. Its role is to start gnunet-services, to
373 re-start them when they crashed and finally to shut down the system when
374 requested.
375 @item @file{peerinfo/} --- peerinfo service
376 The peerinfo service keeps track of which peers are known
377 to the local peer and also tracks the validated addresses for each peer
378 (in the form of a HELLO message) for each of those peers. The peer is not
379 necessarily connected to all peers known to the peerinfo service.
380 Peerinfo provides persistent storage for peer identities --- peers are
381 not forgotten just because of a system restart.
382 @item @file{datacache/} --- libgnunetdatacache
383 The datacache library provides (temporary) block storage for the DHT.
384 Existing plugins can store blocks in Sqlite, Postgres or MySQL databases.
385 All data stored in the cache is lost when the peer is stopped or
386 restarted (datacache uses temporary tables).
387 @item @file{datastore/} --- datastore service
388 The datastore service stores file-sharing blocks in
389 databases for extended periods of time. In contrast to the datacache, data
390 is not lost when peers restart. However, quota restrictions may still
391 cause old, expired or low-priority data to be eventually discarded.
392 Existing plugins can store blocks in Sqlite, Postgres or MySQL databases.
393 @item @file{template/} --- service template
394 Template for writing a new service. Does nothing.
395 @item @file{ats/} --- Automatic Transport Selection
396 The automatic transport selection (ATS) service
397 is responsible for deciding which address (i.e.
398 which transport plugin) should be used for communication with other peers,
399 and at what bandwidth.
400 @item @file{nat/} --- libgnunetnat
401 Library that provides basic functions for NAT traversal.
402 The library supports NAT traversal with
403 manual hole-punching by the user, UPnP and ICMP-based autonomous NAT
404 traversal. The library also includes an API for testing if the current
405 configuration works and the @code{gnunet-nat-server} which provides an
406 external service to test the local configuration.
407 @item @file{fragmentation/} --- libgnunetfragmentation
408 Some transports (UDP and WLAN, mostly) have restrictions on the maximum
409 transfer unit (MTU) for packets. The fragmentation library can be used to
410 break larger packets into chunks of at most 1k and transmit the resulting
411 fragments reliably (with acknowledgment, retransmission, timeouts,
412 etc.).
413 @item @file{transport/} --- transport service
414 The transport service is responsible for managing the
415 basic P2P communication. It uses plugins to support P2P communication
416 over TCP, UDP, HTTP, HTTPS and other protocols.The transport service
417 validates peer addresses, enforces bandwidth restrictions, limits the
418 total number of connections and enforces connectivity restrictions (i.e.
419 friends-only).
420 @item @file{peerinfo-tool/} --- gnunet-peerinfo
421 This directory contains the gnunet-peerinfo binary which can be used to
422 inspect the peers and HELLOs known to the peerinfo service.
423 @item @file{core/}
424 The core service is responsible for establishing encrypted, authenticated
425 connections with other peers, encrypting and decrypting messages and
426 forwarding messages to higher-level services that are interested in them.
427 @item @file{testing/} --- libgnunettesting
428 The testing library allows starting (and stopping) peers
429 for writing testcases.
430 It also supports automatic generation of configurations for peers
431 ensuring that the ports and paths are disjoint. libgnunettesting is also
432 the foundation for the testbed service
433 @item @file{testbed/} --- testbed service
434 The testbed service is used for creating small or large scale deployments
435 of GNUnet peers for evaluation of protocols.
436 It facilitates peer deployments on multiple
437 hosts (for example, in a cluster) and establishing various network
438 topologies (both underlay and overlay).
439 @item @file{nse/} --- Network Size Estimation
440 The network size estimation (NSE) service
441 implements a protocol for (securely) estimating the current size of the
442 P2P network.
443 @item @file{dht/} --- distributed hash table
444 The distributed hash table (DHT) service provides a
445 distributed implementation of a hash table to store blocks under hash
446 keys in the P2P network.
447 @item @file{hostlist/} --- hostlist service
448 The hostlist service allows learning about
449 other peers in the network by downloading HELLO messages from an HTTP
450 server, can be configured to run such an HTTP server and also implements
451 a P2P protocol to advertise and automatically learn about other peers
452 that offer a public hostlist server.
453 @item @file{topology/} --- topology service
454 The topology service is responsible for
455 maintaining the mesh topology. It tries to maintain connections to friends
456 (depending on the configuration) and also tries to ensure that the peer
457 has a decent number of active connections at all times. If necessary, new
458 connections are added. All peers should run the topology service,
459 otherwise they may end up not being connected to any other peer (unless
460 some other service ensures that core establishes the required
461 connections). The topology service also tells the transport service which
462 connections are permitted (for friend-to-friend networking)
463 @item @file{fs/} --- file-sharing
464 The file-sharing (FS) service implements GNUnet's
465 file-sharing application. Both anonymous file-sharing (using gap) and
466 non-anonymous file-sharing (using dht) are supported.
467 @item @file{cadet/} --- cadet service
468 The CADET service provides a general-purpose routing abstraction to create
469 end-to-end encrypted tunnels in mesh networks. We wrote a paper
470 documenting key aspects of the design.
471 @item @file{tun/} --- libgnunettun
472 Library for building IPv4, IPv6 packets and creating
473 checksums for UDP, TCP and ICMP packets. The header
474 defines C structs for common Internet packet formats and in particular
475 structs for interacting with TUN (virtual network) interfaces.
476 @item @file{mysql/} --- libgnunetmysql
477 Library for creating and executing prepared MySQL
478 statements and to manage the connection to the MySQL database.
479 Essentially a lightweight wrapper for the interaction between GNUnet
480 components and libmysqlclient.
481 @item @file{dns/}
482 Service that allows intercepting and modifying DNS requests of
483 the local machine. Currently used for IPv4-IPv6 protocol translation
484 (DNS-ALG) as implemented by "pt/" and for the GNUnet naming system. The
485 service can also be configured to offer an exit service for DNS traffic.
486 @item @file{vpn/} --- VPN service
487 The virtual public network (VPN) service provides a virtual
488 tunnel interface (VTUN) for IP routing over GNUnet.
489 Needs some other peers to run an "exit" service to work.
490 Can be activated using the "gnunet-vpn" tool or integrated with DNS using
491 the "pt" daemon.
492 @item @file{exit/}
493 Daemon to allow traffic from the VPN to exit this
494 peer to the Internet or to specific IP-based services of the local peer.
495 Currently, an exit service can only be restricted to IPv4 or IPv6, not to
496 specific ports and or IP address ranges. If this is not acceptable,
497 additional firewall rules must be added manually. exit currently only
498 works for normal UDP, TCP and ICMP traffic; DNS queries need to leave the
499 system via a DNS service.
500 @item @file{pt/}
501 protocol translation daemon. This daemon enables 4-to-6,
502 6-to-4, 4-over-6 or 6-over-4 transitions for the local system. It
503 essentially uses "DNS" to intercept DNS replies and then maps results to
504 those offered by the VPN, which then sends them using mesh to some daemon
505 offering an appropriate exit service.
506 @item @file{identity/}
507 Management of egos (alter egos) of a user; identities are
508 essentially named ECC private keys and used for zones in the GNU name
509 system and for namespaces in file-sharing, but might find other uses later
510 @item @file{revocation/}
511 Key revocation service, can be used to revoke the
512 private key of an identity if it has been compromised
513 @item @file{namecache/}
514 Cache for resolution results for the GNU name system;
515 data is encrypted and can be shared among users,
516 loss of the data should ideally only result in a
517 performance degradation (persistence not required)
518 @item @file{namestore/}
519 Database for the GNU name system with per-user private information,
520 persistence required
521 @item @file{gns/}
522 GNU name system, a GNU approach to DNS and PKI.
523 @item @file{dv/}
524 A plugin for distance-vector (DV)-based routing.
525 DV consists of a service and a transport plugin to provide peers
526 with the illusion of a direct P2P connection for connections
527 that use multiple (typically up to 3) hops in the actual underlay network.
528 @item @file{regex/}
529 Service for the (distributed) evaluation of regular expressions.
530 @item @file{scalarproduct/}
531 The scalar product service offers an API to perform a secure multiparty
532 computation which calculates a scalar product between two peers
533 without exposing the private input vectors of the peers to each other.
534 @item @file{consensus/}
535 The consensus service will allow a set of peers to agree
536 on a set of values via a distributed set union computation.
537 @item @file{rest/}
538 The rest API allows access to GNUnet services using RESTful interaction.
539 The services provide plugins that can exposed by the rest server.
540 @c FIXME: Where did this disappear to?
541 @c @item @file{experimentation/}
542 @c The experimentation daemon coordinates distributed
543 @c experimentation to evaluate transport and ATS properties.
544 @end table
545
546 @c ***********************************************************************
547 @node System Architecture
548 @section System Architecture
549
550 @c FIXME: For those irritated by the textflow, we are missing images here,
551 @c in the short term we should add them back, in the long term this should
552 @c work without images or have images with alt-text.
553
554 GNUnet developers like LEGOs. The blocks are indestructible, can be
555 stacked together to construct complex buildings and it is generally easy
556 to swap one block for a different one that has the same shape. GNUnet's
557 architecture is based on LEGOs:
558
559 @image{images/service_lego_block,5in,,picture of a LEGO block stack - 3 APIs upon IPC/network protocol provided by a service}
560
561 This chapter documents the GNUnet LEGO system, also known as GNUnet's
562 system architecture.
563
564 The most common GNUnet component is a service. Services offer an API (or
565 several, depending on what you count as "an API") which is implemented as
566 a library. The library communicates with the main process of the service
567 using a service-specific network protocol. The main process of the service
568 typically doesn't fully provide everything that is needed --- it has holes
569 to be filled by APIs to other services.
570
571 A special kind of component in GNUnet are user interfaces and daemons.
572 Like services, they have holes to be filled by APIs of other services.
573 Unlike services, daemons do not implement their own network protocol and
574 they have no API:
575
576 @image{images/daemon_lego_block,5in,,A daemon in GNUnet is a component that does not offer an API for others to build upon}
577
578 The GNUnet system provides a range of services, daemons and user
579 interfaces, which are then combined into a layered GNUnet instance (also
580 known as a peer).
581
582 @image{images/service_stack,5in,,A GNUnet peer consists of many layers of services}
583
584 Note that while it is generally possible to swap one service for another
585 compatible service, there is often only one implementation. However,
586 during development we often have a "new" version of a service in parallel
587 with an "old" version. While the "new" version is not working, developers
588 working on other parts of the service can continue their development by
589 simply using the "old" service. Alternative design ideas can also be
590 easily investigated by swapping out individual components. This is
591 typically achieved by simply changing the name of the "BINARY" in the
592 respective configuration section.
593
594 Key properties of GNUnet services are that they must be separate        
595 processes and that they must protect themselves by applying tight error
596 checking against the network protocol they implement (thereby achieving a
597 certain degree of robustness).
598
599 On the other hand, the APIs are implemented to tolerate failures of the
600 service, isolating their host process from errors by the service. If the
601 service process crashes, other services and daemons around it should not
602 also fail, but instead wait for the service process to be restarted by
603 ARM.
604
605
606 @c ***********************************************************************
607 @node Subsystem stability
608 @section Subsystem stability
609
610 This section documents the current stability of the various GNUnet
611 subsystems. Stability here describes the expected degree of compatibility
612 with future versions of GNUnet. For each subsystem we distinguish between
613 compatibility on the P2P network level (communication protocol between
614 peers), the IPC level (communication between the service and the service
615 library) and the API level (stability of the API). P2P compatibility is
616 relevant in terms of which applications are likely going to be able to
617 communicate with future versions of the network. IPC communication is
618 relevant for the implementation of language bindings that re-implement the
619 IPC messages. Finally, API compatibility is relevant to developers that
620 hope to be able to avoid changes to applications build on top of the APIs
621 of the framework.
622
623 The following table summarizes our current view of the stability of the
624 respective protocols or APIs:
625
626 @multitable @columnfractions .20 .20 .20 .20
627 @headitem Subsystem @tab P2P @tab IPC @tab C API
628 @item util @tab n/a @tab n/a @tab stable
629 @item arm @tab n/a @tab stable @tab stable
630 @item ats @tab n/a @tab unstable @tab testing
631 @item block @tab n/a @tab n/a @tab stable
632 @item cadet @tab testing @tab testing @tab testing
633 @item consensus @tab experimental @tab experimental @tab experimental
634 @item core @tab stable @tab stable @tab stable
635 @item datacache @tab n/a @tab n/a @tab stable
636 @item datastore @tab n/a @tab stable @tab stable
637 @item dht @tab stable @tab stable @tab stable
638 @item dns @tab stable @tab stable @tab stable
639 @item dv @tab testing @tab testing @tab n/a
640 @item exit @tab testing @tab n/a @tab n/a
641 @item fragmentation @tab stable @tab n/a @tab stable
642 @item fs @tab stable @tab stable @tab stable
643 @item gns @tab stable @tab stable @tab stable
644 @item hello @tab n/a @tab n/a @tab testing
645 @item hostlist @tab stable @tab stable @tab n/a
646 @item identity @tab stable @tab stable @tab n/a
647 @item multicast @tab experimental @tab experimental @tab experimental
648 @item mysql @tab stable @tab n/a @tab stable
649 @item namestore @tab n/a @tab stable @tab stable
650 @item nat @tab n/a @tab n/a @tab stable
651 @item nse @tab stable @tab stable @tab stable
652 @item peerinfo @tab n/a @tab stable @tab stable
653 @item psyc @tab experimental @tab experimental @tab experimental
654 @item pt @tab n/a @tab n/a @tab n/a
655 @item regex @tab stable @tab stable @tab stable
656 @item revocation @tab stable @tab stable @tab stable
657 @item social @tab experimental @tab experimental @tab experimental
658 @item statistics @tab n/a @tab stable @tab stable
659 @item testbed @tab n/a @tab testing @tab testing
660 @item testing @tab n/a @tab n/a @tab testing
661 @item topology @tab n/a @tab n/a @tab n/a
662 @item transport @tab stable @tab stable @tab stable
663 @item tun @tab n/a @tab n/a @tab stable
664 @item vpn @tab testing @tab n/a @tab n/a
665 @end multitable
666
667 Here is a rough explanation of the values:
668
669 @table @samp
670 @item stable
671 No incompatible changes are planned at this time; for IPC/APIs, if
672 there are incompatible changes, they will be minor and might only require
673 minimal changes to existing code; for P2P, changes will be avoided if at
674 all possible for the 0.10.x-series
675
676 @item testing
677 No incompatible changes are
678 planned at this time, but the code is still known to be in flux; so while
679 we have no concrete plans, our expectation is that there will still be
680 minor modifications; for P2P, changes will likely be extensions that
681 should not break existing code
682
683 @item unstable
684 Changes are planned and will happen; however, they
685 will not be totally radical and the result should still resemble what is
686 there now; nevertheless, anticipated changes will break protocol/API
687 compatibility
688
689 @item experimental
690 Changes are planned and the result may look nothing like
691 what the API/protocol looks like today
692
693 @item unknown
694 Someone should think about where this subsystem headed
695
696 @item n/a
697 This subsystem does not have an API/IPC-protocol/P2P-protocol
698 @end table
699
700 @c ***********************************************************************
701 @node Naming conventions and coding style guide
702 @section Naming conventions and coding style guide
703
704 Here you can find some rules to help you write code for GNUnet.
705
706 @c ***********************************************************************
707 @menu
708 * Naming conventions::
709 * Coding style::
710 @end menu
711
712 @node Naming conventions
713 @subsection Naming conventions
714
715
716 @c ***********************************************************************
717 @menu
718 * include files::
719 * binaries::
720 * logging::
721 * configuration::
722 * exported symbols::
723 * private (library-internal) symbols (including structs and macros)::
724 * testcases::
725 * performance tests::
726 * src/ directories::
727 @end menu
728
729 @node include files
730 @subsubsection include files
731
732 @itemize @bullet
733 @item _lib: library without need for a process
734 @item _service: library that needs a service process
735 @item _plugin: plugin definition
736 @item _protocol: structs used in network protocol
737 @item exceptions:
738 @itemize @bullet
739 @item gnunet_config.h --- generated
740 @item platform.h --- first included
741 @item plibc.h --- external library
742 @item gnunet_common.h --- fundamental routines
743 @item gnunet_directories.h --- generated
744 @item gettext.h --- external library
745 @end itemize
746 @end itemize
747
748 @c ***********************************************************************
749 @node binaries
750 @subsubsection binaries
751
752 @itemize @bullet
753 @item gnunet-service-xxx: service process (has listen socket)
754 @item gnunet-daemon-xxx: daemon process (no listen socket)
755 @item gnunet-helper-xxx[-yyy]: SUID helper for module xxx
756 @item gnunet-yyy: command-line tool for end-users
757 @item libgnunet_plugin_xxx_yyy.so: plugin for API xxx
758 @item libgnunetxxx.so: library for API xxx
759 @end itemize
760
761 @c ***********************************************************************
762 @node logging
763 @subsubsection logging
764
765 @itemize @bullet
766 @item services and daemons use their directory name in
767 @code{GNUNET_log_setup} (i.e. 'core') and log using
768 plain 'GNUNET_log'.
769 @item command-line tools use their full name in
770 @code{GNUNET_log_setup} (i.e. 'gnunet-publish') and log using
771 plain 'GNUNET_log'.
772 @item service access libraries log using
773 '@code{GNUNET_log_from}' and use '@code{DIRNAME-api}' for the
774 component (i.e. 'core-api')
775 @item pure libraries (without associated service) use
776 '@code{GNUNET_log_from}' with the component set to their
777 library name (without lib or '@file{.so}'),
778 which should also be their directory name (i.e. '@file{nat}')
779 @item plugins should use '@code{GNUNET_log_from}'
780 with the directory name and the plugin name combined to produce
781 the component name (i.e. 'transport-tcp').
782 @item logging should be unified per-file by defining a
783 @code{LOG} macro with the appropriate arguments,
784 along these lines:
785
786 @example
787 #define LOG(kind,...)
788 GNUNET_log_from (kind, "example-api",__VA_ARGS__)
789 @end example
790
791 @end itemize
792
793 @c ***********************************************************************
794 @node configuration
795 @subsubsection configuration
796
797 @itemize @bullet
798 @item paths (that are substituted in all filenames) are in PATHS
799 (have as few as possible)
800 @item all options for a particular module (@file{src/MODULE})
801 are under @code{[MODULE]}
802 @item options for a plugin of a module
803 are under @code{[MODULE-PLUGINNAME]}
804 @end itemize
805
806 @c ***********************************************************************
807 @node exported symbols
808 @subsubsection exported symbols
809
810 @itemize @bullet
811 @item must start with @code{GNUNET_modulename_} and be defined in
812 @file{modulename.c}
813 @item exceptions: those defined in @file{gnunet_common.h}
814 @end itemize
815
816 @c ***********************************************************************
817 @node private (library-internal) symbols (including structs and macros)
818 @subsubsection private (library-internal) symbols (including structs and macros)
819
820 @itemize @bullet
821 @item must NOT start with any prefix
822 @item must not be exported in a way that linkers could use them or@ other
823 libraries might see them via headers; they must be either
824 declared/defined in C source files or in headers that are in the
825 respective directory under @file{src/modulename/} and NEVER be declared
826 in @file{src/include/}.
827 @end itemize
828
829 @node testcases
830 @subsubsection testcases
831
832 @itemize @bullet
833 @item must be called @file{test_module-under-test_case-description.c}
834 @item "case-description" maybe omitted if there is only one test
835 @end itemize
836
837 @c ***********************************************************************
838 @node performance tests
839 @subsubsection performance tests
840
841 @itemize @bullet
842 @item must be called @file{perf_module-under-test_case-description.c}
843 @item "case-description" maybe omitted if there is only one performance
844 test
845 @item Must only be run if @code{HAVE_BENCHMARKS} is satisfied
846 @end itemize
847
848 @c ***********************************************************************
849 @node src/ directories
850 @subsubsection src/ directories
851
852 @itemize @bullet
853 @item gnunet-NAME: end-user applications (i.e., gnunet-search, gnunet-arm)
854 @item gnunet-service-NAME: service processes with accessor library (i.e.,
855 gnunet-service-arm)
856 @item libgnunetNAME: accessor library (_service.h-header) or standalone
857 library (_lib.h-header)
858 @item gnunet-daemon-NAME: daemon process without accessor library (i.e.,
859 gnunet-daemon-hostlist) and no GNUnet management port
860 @item libgnunet_plugin_DIR_NAME: loadable plugins (i.e.,
861 libgnunet_plugin_transport_tcp)
862 @end itemize
863
864 @cindex Coding style
865 @node Coding style
866 @subsection Coding style
867
868 @c XXX: Adjust examples to GNU Standards!
869 @itemize @bullet
870 @item We follow the GNU Coding Standards (@pxref{Top, The GNU Coding Standards,, standards, The GNU Coding Standards});
871 @item Indentation is done with spaces, two per level, no tabs;
872 @item C99 struct initialization is fine;
873 @item declare only one variable per line, for example:
874
875 @noindent
876 instead of
877
878 @example
879 int i,j;
880 @end example
881
882 @noindent
883 write:
884
885 @example
886 int i;
887 int j;
888 @end example
889
890 @c TODO: include actual example from a file in source
891
892 @noindent
893 This helps keep diffs small and forces developers to think precisely about
894 the type of every variable.
895 Note that @code{char *} is different from @code{const char*} and
896 @code{int} is different from @code{unsigned int} or @code{uint32_t}.
897 Each variable type should be chosen with care.
898
899 @item While @code{goto} should generally be avoided, having a
900 @code{goto} to the end of a function to a block of clean up
901 statements (free, close, etc.) can be acceptable.
902
903 @item Conditions should be written with constants on the left (to avoid
904 accidental assignment) and with the @code{true} target being either the
905 @code{error} case or the significantly simpler continuation. For example:
906
907 @example
908 if (0 != stat ("filename,"
909                &sbuf))
910 @{
911   error();
912 @}
913 else
914 @{
915   /* handle normal case here */
916 @}
917 @end example
918
919 @noindent
920 instead of
921
922 @example
923 if (stat ("filename," &sbuf) == 0) @{
924   /* handle normal case here */
925  @} else @{
926   error();
927  @}
928 @end example
929
930 @noindent
931 If possible, the error clause should be terminated with a @code{return} (or
932 @code{goto} to some cleanup routine) and in this case, the @code{else} clause
933 should be omitted:
934
935 @example
936 if (0 != stat ("filename",
937                &sbuf))
938 @{
939   error();
940   return;
941 @}
942 /* handle normal case here */
943 @end example
944
945 This serves to avoid deep nesting. The 'constants on the left' rule
946 applies to all constants (including. @code{GNUNET_SCHEDULER_NO_TASK}),
947 NULL, and enums). With the two above rules (constants on left, errors in
948 'true' branch), there is only one way to write most branches correctly.
949
950 @item Combined assignments and tests are allowed if they do not hinder
951 code clarity. For example, one can write:
952
953 @example
954 if (NULL == (value = lookup_function()))
955 @{
956   error();
957   return;
958 @}
959 @end example
960
961 @item Use @code{break} and @code{continue} wherever possible to avoid
962 deep(er) nesting. Thus, we would write:
963
964 @example
965 next = head;
966 while (NULL != (pos = next))
967 @{
968   next = pos->next;
969   if (! should_free (pos))
970     continue;
971   GNUNET_CONTAINER_DLL_remove (head,
972                                tail,
973                                pos);
974   GNUNET_free (pos);
975 @}
976 @end example
977
978 instead of
979
980 @example
981 next = head; while (NULL != (pos = next)) @{
982   next = pos->next;
983   if (should_free (pos)) @{
984     /* unnecessary nesting! */
985     GNUNET_CONTAINER_DLL_remove (head, tail, pos);
986     GNUNET_free (pos);
987    @}
988   @}
989 @end example
990
991 @item We primarily use @code{for} and @code{while} loops.
992 A @code{while} loop is used if the method for advancing in the loop is
993 not a straightforward increment operation. In particular, we use:
994
995 @example
996 next = head;
997 while (NULL != (pos = next))
998 @{
999   next = pos->next;
1000   if (! should_free (pos))
1001     continue;
1002   GNUNET_CONTAINER_DLL_remove (head,
1003                                tail,
1004                                pos);
1005   GNUNET_free (pos);
1006 @}
1007 @end example
1008
1009 to free entries in a list (as the iteration changes the structure of the
1010 list due to the free; the equivalent @code{for} loop does no longer
1011 follow the simple @code{for} paradigm of @code{for(INIT;TEST;INC)}).
1012 However, for loops that do follow the simple @code{for} paradigm we do
1013 use @code{for}, even if it involves linked lists:
1014
1015 @example
1016 /* simple iteration over a linked list */
1017 for (pos = head;
1018      NULL != pos;
1019      pos = pos->next)
1020 @{
1021    use (pos);
1022 @}
1023 @end example
1024
1025
1026 @item The first argument to all higher-order functions in GNUnet must be
1027 declared to be of type @code{void *} and is reserved for a closure. We do
1028 not use inner functions, as trampolines would conflict with setups that
1029 use non-executable stacks.
1030 The first statement in a higher-order function, which unusually should
1031 be part of the variable declarations, should assign the
1032 @code{cls} argument to the precise expected type. For example:
1033
1034 @example
1035 int
1036 callback (void *cls,
1037           char *args)
1038 @{
1039   struct Foo *foo = cls;
1040   int other_variables;
1041
1042    /* rest of function */
1043 @}
1044 @end example
1045
1046 @item As shown in the example above, after the return type of a
1047 function there should be a break.  Each parameter should
1048 be on a new line.
1049
1050 @item It is good practice to write complex @code{if} expressions instead
1051 of using deeply nested @code{if} statements. However, except for addition
1052 and multiplication, all operators should use parens. This is fine:
1053
1054 @example
1055 if ( (1 == foo) ||
1056      ( (0 == bar) &&
1057        (x != y) ) )
1058   return x;
1059 @end example
1060
1061
1062 However, this is not:
1063
1064 @example
1065 if (1 == foo)
1066   return x;
1067 if (0 == bar && x != y)
1068   return x;
1069 @end example
1070
1071 @noindent
1072 Note that splitting the @code{if} statement above is debatable as the
1073 @code{return x} is a very trivial statement. However, once the logic after
1074 the branch becomes more complicated (and is still identical), the "or"
1075 formulation should be used for sure.
1076
1077 @item There should be two empty lines between the end of the function and
1078 the comments describing the following function. There should be a single
1079 empty line after the initial variable declarations of a function. If a
1080 function has no local variables, there should be no initial empty line. If
1081 a long function consists of several complex steps, those steps might be
1082 separated by an empty line (possibly followed by a comment describing the
1083 following step). The code should not contain empty lines in arbitrary
1084 places; if in doubt, it is likely better to NOT have an empty line (this
1085 way, more code will fit on the screen).
1086 @end itemize
1087
1088 @c ***********************************************************************
1089 @node Build-system
1090 @section Build-system
1091
1092 If you have code that is likely not to compile or build rules you might
1093 want to not trigger for most developers, use @code{if HAVE_EXPERIMENTAL}
1094 in your @file{Makefile.am}.
1095 Then it is OK to (temporarily) add non-compiling (or known-to-not-port)
1096 code.
1097
1098 If you want to compile all testcases but NOT run them, run configure with
1099 the @code{--enable-test-suppression} option.
1100
1101 If you want to run all testcases, including those that take a while, run
1102 configure with the @code{--enable-expensive-testcases} option.
1103
1104 If you want to compile and run benchmarks, run configure with the
1105 @code{--enable-benchmarks} option.
1106
1107 If you want to obtain code coverage results, run configure with the
1108 @code{--enable-coverage} option and run the @file{coverage.sh} script in
1109 the @file{contrib/} directory.
1110
1111 @cindex gnunet-ext
1112 @node Developing extensions for GNUnet using the gnunet-ext template
1113 @section Developing extensions for GNUnet using the gnunet-ext template
1114
1115 For developers who want to write extensions for GNUnet we provide the
1116 gnunet-ext template to provide an easy to use skeleton.
1117
1118 gnunet-ext contains the build environment and template files for the
1119 development of GNUnet services, command line tools, APIs and tests.
1120
1121 First of all you have to obtain gnunet-ext from git:
1122
1123 @example
1124 git clone https://git.gnunet.org/gnunet-ext.git
1125 @end example
1126
1127 The next step is to bootstrap and configure it. For configure you have to
1128 provide the path containing GNUnet with
1129 @code{--with-gnunet=/path/to/gnunet} and the prefix where you want the
1130 install the extension using @code{--prefix=/path/to/install}:
1131
1132 @example
1133 ./bootstrap
1134 ./configure --prefix=/path/to/install --with-gnunet=/path/to/gnunet
1135 @end example
1136
1137 When your GNUnet installation is not included in the default linker search
1138 path, you have to add @code{/path/to/gnunet} to the file
1139 @file{/etc/ld.so.conf} and run @code{ldconfig} or your add it to the
1140 environmental variable @code{LD_LIBRARY_PATH} by using
1141
1142 @example
1143 export LD_LIBRARY_PATH=/path/to/gnunet/lib
1144 @end example
1145
1146 @cindex writing testcases
1147 @node Writing testcases
1148 @section Writing testcases
1149
1150 Ideally, any non-trivial GNUnet code should be covered by automated
1151 testcases. Testcases should reside in the same place as the code that is
1152 being tested. The name of source files implementing tests should begin
1153 with @code{test_} followed by the name of the file that contains
1154 the code that is being tested.
1155
1156 Testcases in GNUnet should be integrated with the autotools build system.
1157 This way, developers and anyone building binary packages will be able to
1158 run all testcases simply by running @code{make check}. The final
1159 testcases shipped with the distribution should output at most some brief
1160 progress information and not display debug messages by default. The
1161 success or failure of a testcase must be indicated by returning zero
1162 (success) or non-zero (failure) from the main method of the testcase.
1163 The integration with the autotools is relatively straightforward and only
1164 requires modifications to the @file{Makefile.am} in the directory
1165 containing the testcase. For a testcase testing the code in @file{foo.c}
1166 the @file{Makefile.am} would contain the following lines:
1167
1168 @example
1169 check_PROGRAMS = test_foo
1170 TESTS = $(check_PROGRAMS)
1171 test_foo_SOURCES = test_foo.c
1172 test_foo_LDADD = $(top_builddir)/src/util/libgnunetutil.la
1173 @end example
1174
1175 Naturally, other libraries used by the testcase may be specified in the
1176 @code{LDADD} directive as necessary.
1177
1178 Often testcases depend on additional input files, such as a configuration
1179 file. These support files have to be listed using the @code{EXTRA_DIST}
1180 directive in order to ensure that they are included in the distribution.
1181
1182 Example:
1183
1184 @example
1185 EXTRA_DIST = test_foo_data.conf
1186 @end example
1187
1188 Executing @code{make check} will run all testcases in the current
1189 directory and all subdirectories. Testcases can be compiled individually
1190 by running @code{make test_foo} and then invoked directly using
1191 @code{./test_foo}. Note that due to the use of plugins in GNUnet, it is
1192 typically necessary to run @code{make install} before running any
1193 testcases. Thus the canonical command @code{make check install} has to be
1194 changed to @code{make install check} for GNUnet.
1195
1196 @c ***********************************************************************
1197 @cindex Building GNUnet
1198 @node Building GNUnet and its dependencies
1199 @section Building GNUnet and its dependencies
1200
1201 In the following section we will outline how to build GNUnet and
1202 some of its dependencies. We will assume a fair amount of knowledge
1203 for building applications under UNIX-like systems. Furthermore we
1204 assume that the build environment is sane and that you are aware of
1205 any implications actions in this process could have.
1206 Instructions here can be seen as notes for developers (an extension to
1207 the 'HACKING' section in README) as well as package maintainers.
1208 @b{Users should rely on the available binary packages.}
1209 We will use Debian as an example Operating System environment. Substitute
1210 accordingly with your own Operating System environment.
1211
1212 For the full list of dependencies, consult the appropriate, up-to-date
1213 section in the @file{README} file.
1214
1215 First, we need to build or install (depending on your OS) the following
1216 packages. If you build them from source, build them in this exact order:
1217
1218 @example
1219 libgpgerror, libgcrypt, libnettle, libunbound, GnuTLS (with libunbound
1220 support)
1221 @end example
1222
1223 After we have build and installed those packages, we continue with
1224 packages closer to GNUnet in this step: libgnurl (our libcurl fork),
1225 GNU libmicrohttpd, and GNU libextractor. Again, if your package manager
1226 provides one of these packages, use the packages provided from it
1227 unless you have good reasons (package version too old, conflicts, etc).
1228 We advise against compiling widely used packages such as GnuTLS
1229 yourself if your OS provides a variant already unless you take care
1230 of maintenance of the packages then.
1231
1232 In the optimistic case, this command will give you all the dependencies:
1233
1234 @example
1235 sudo apt-get install libgnurl libmicrohttpd libextractor
1236 @end example
1237
1238 From experience we know that at the very least libgnurl is not
1239 available in some environments. You could substitute libgnurl
1240 with libcurl, but we recommend to install libgnurl, as it gives
1241 you a predefined libcurl with the small set GNUnet requires. In
1242 the past namespaces of libcurl and libgnurl were shared, which
1243 caused problems when you wanted to integrate both of them in one
1244 Operating System. This has been resolved, and they can be installed
1245 side by side now.
1246
1247 @cindex libgnurl
1248 @cindex compiling libgnurl
1249 GNUnet and some of its function depend on a limited subset of cURL/libcurl.
1250 Rather than trying to enforce a certain configuration on the world, we
1251 opted to maintain a microfork of it that ensures we can link against the
1252 right set of features. We called this specialized set of libcurl
1253 ``libgnurl''. It is fully ABI compatible with libcurl and currently used
1254 by GNUnet and some of its dependencies.
1255
1256 We download libgnurl and its digital signature from the GNU fileserver,
1257 assuming @env{TMPDIR} exists.
1258
1259 Note: TMPDIR might be @file{/tmp}, @env{TMPDIR}, @env{TMP} or any other
1260 location. For consistency we assume @env{TMPDIR} points to @file{/tmp}
1261 for the remainder of this section.
1262
1263 @example
1264 cd \$TMPDIR
1265 wget https://ftp.gnu.org/gnu/gnunet/gnurl-7.60.0.tar.Z
1266 wget https://ftp.gnu.org/gnu/gnunet/gnurl-7.60.0.tar.Z.sig
1267 @end example
1268
1269 Next, verify the digital signature of the file:
1270
1271 @example
1272 gpg --verify gnurl-7.60.0.tar.Z.sig
1273 @end example
1274
1275 If gpg fails, you might try with @command{gpg2} on your OS. If the error
1276 states that ``the key can not be found'' or it is unknown, you have to
1277 retrieve the key (A88C8ADD129828D7EAC02E52E22F9BBFEE348588) from a
1278 keyserver first:
1279
1280 @example
1281 gpg --keyserver pgp.mit.edu --recv-keys A88C8ADD129828D7EAC02E52E22F9BBFEE348588
1282 @end example
1283
1284 and rerun the verification command.
1285
1286 libgnurl will require the following packages to be present at runtime:
1287 gnutls (with DANE support / libunbound), libidn, zlib and at compile time:
1288 libtool, groff, perl, pkg-config, and python 2.7.
1289
1290 Once you have verified that all the required packages are present on your
1291 system, we can proceed to compile libgnurl:
1292
1293 @example
1294 tar -xvf gnurl-7.60.0.tar.Z
1295 cd gnurl-7.60.0
1296 sh configure --disable-ntlm-wb
1297 make
1298 make -C tests test
1299 sudo make install
1300 @end example
1301
1302 After you've compiled and installed libgnurl, we can proceed to building
1303 GNUnet.
1304
1305
1306
1307
1308 First, in addition to the GNUnet sources you might require downloading the
1309 latest version of various dependencies, depending on how recent the
1310 software versions in your distribution of GNU/Linux are.
1311 Most distributions do not include sufficiently recent versions of these
1312 dependencies.
1313 Thus, a typically installation on a "modern" GNU/Linux distribution
1314 requires you to install the following dependencies (ideally in this
1315 order):
1316
1317 @itemize @bullet
1318 @item libgpgerror and libgcrypt
1319 @item libnettle and libunbound (possibly from distribution), GnuTLS
1320 @item libgnurl (read the README)
1321 @item GNU libmicrohttpd
1322 @item GNU libextractor
1323 @end itemize
1324
1325 Make sure to first install the various mandatory and optional
1326 dependencies including development headers from your distribution.
1327
1328 Other dependencies that you should strongly consider to install is a
1329 database (MySQL, sqlite or Postgres).
1330 The following instructions will assume that you installed at least sqlite.
1331 For most distributions you should be able to find pre-build packages for
1332 the database. Again, make sure to install the client libraries @b{and} the
1333 respective development headers (if they are packaged separately) as well.
1334
1335 You can find specific, detailed instructions for installing of the
1336 dependencies (and possibly the rest of the GNUnet installation) in the
1337 platform-specific descriptions, which can be found in the Index.
1338 Please consult them now.
1339 If your distribution is not listed, please study the build
1340 instructions for Debian stable, carefully as you try to install the
1341 dependencies for your own distribution.
1342 Contributing additional instructions for further platforms is always
1343 appreciated.
1344 Please take in mind that operating system development tends to move at
1345 a rather fast speed. Due to this you should be aware that some of
1346 the instructions could be outdated by the time you are reading this.
1347 If you find a mistake, please tell us about it (or even better: send
1348 a patch to the documentation to fix it!).
1349
1350 Before proceeding further, please double-check the dependency list.
1351 Note that in addition to satisfying the dependencies, you might have to
1352 make sure that development headers for the various libraries are also
1353 installed.
1354 There maybe files for other distributions, or you might be able to find
1355 equivalent packages for your distribution.
1356
1357 While it is possible to build and install GNUnet without having root
1358 access, we will assume that you have full control over your system in
1359 these instructions.
1360 First, you should create a system user @emph{gnunet} and an additional
1361 group @emph{gnunetdns}. On the GNU/Linux distributions Debian and Ubuntu,
1362 type:
1363
1364 @example
1365 sudo adduser --system --home /var/lib/gnunet --group \
1366 --disabled-password gnunet
1367 sudo addgroup --system gnunetdns
1368 @end example
1369
1370 @noindent
1371 On other Unixes and GNU systems, this should have the same effect:
1372
1373 @example
1374 sudo useradd --system --groups gnunet --home-dir /var/lib/gnunet
1375 sudo addgroup --system gnunetdns
1376 @end example
1377
1378 Now compile and install GNUnet using:
1379
1380 @example
1381 tar xvf gnunet-@value{VERSION}.tar.gz
1382 cd gnunet-@value{VERSION}
1383 ./configure --with-sudo=sudo --with-nssdir=/lib
1384 make
1385 sudo make install
1386 @end example
1387
1388 If you want to be able to enable DEBUG-level log messages, add
1389 @code{--enable-logging=verbose} to the end of the
1390 @command{./configure} command.
1391 @code{DEBUG}-level log messages are in English only and
1392 should only be useful for developers (or for filing
1393 really detailed bug reports).
1394
1395 @noindent
1396 Next, edit the file @file{/etc/gnunet.conf} to contain the following:
1397
1398 @example
1399 [arm]
1400 START_SYSTEM_SERVICES = YES
1401 START_USER_SERVICES = NO
1402 @end example
1403
1404 @noindent
1405 You may need to update your @code{ld.so} cache to include
1406 files installed in @file{/usr/local/lib}:
1407
1408 @example
1409 # ldconfig
1410 @end example
1411
1412 @noindent
1413 Then, switch from user @code{root} to user @code{gnunet} to start
1414 the peer:
1415
1416 @example
1417 # su -s /bin/sh - gnunet
1418 $ gnunet-arm -c /etc/gnunet.conf -s
1419 @end example
1420
1421 You may also want to add the last line in the gnunet user's @file{crontab}
1422 prefixed with @code{@@reboot} so that it is executed whenever the system
1423 is booted:
1424
1425 @example
1426 @@reboot /usr/local/bin/gnunet-arm -c /etc/gnunet.conf -s
1427 @end example
1428
1429 @noindent
1430 This will only start the system-wide GNUnet services.
1431 Type @command{exit} to get back your root shell.
1432 Now, you need to configure the per-user part. For each
1433 user that should get access to GNUnet on the system, run
1434 (replace alice with your username):
1435
1436 @example
1437 sudo adduser alice gnunet
1438 @end example
1439
1440 @noindent
1441 to allow them to access the system-wide GNUnet services. Then, each
1442 user should create a configuration file @file{~/.config/gnunet.conf}
1443 with the lines:
1444
1445 @example
1446 [arm]
1447 START_SYSTEM_SERVICES = NO
1448 START_USER_SERVICES = YES
1449 DEFAULTSERVICES = gns
1450 @end example
1451
1452 @noindent
1453 and start the per-user services using
1454
1455 @example
1456 $ gnunet-arm -c ~/.config/gnunet.conf -s
1457 @end example
1458
1459 @noindent
1460 Again, adding a @code{crontab} entry to autostart the peer is advised:
1461
1462 @example
1463 @@reboot /usr/local/bin/gnunet-arm -c $HOME/.config/gnunet.conf -s
1464 @end example
1465
1466 @noindent
1467 Note that some GNUnet services (such as SOCKS5 proxies) may need a
1468 system-wide TCP port for each user.
1469 For those services, systems with more than one user may require each user
1470 to specify a different port number in their personal configuration file.
1471
1472 Finally, the user should perform the basic initial setup for the GNU Name
1473 System (GNS) certificate authority. This is done by running:
1474
1475 @example
1476 $ gnunet-gns-proxy-setup-ca
1477 @end example
1478
1479 @noindent
1480 The first generates the default zones, whereas the second setups the GNS
1481 Certificate Authority with the user's browser. Now, to activate GNS in the
1482 normal DNS resolution process, you need to edit your
1483 @file{/etc/nsswitch.conf} where you should find a line like this:
1484
1485 @example
1486 hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4
1487 @end example
1488
1489 @noindent
1490 The exact details may differ a bit, which is fine. Add the text
1491 @emph{"gns [NOTFOUND=return]"} after @emph{"files"}.
1492 Keep in mind that we included a backslash ("\") here just for
1493 markup reasons. You should write the text below on @b{one line}
1494 and @b{without} the "\":
1495
1496 @example
1497 hosts: files gns [NOTFOUND=return] mdns4_minimal \
1498 [NOTFOUND=return] dns mdns4
1499 @end example
1500
1501 @c FIXME: Document new behavior.
1502 You might want to make sure that @file{/lib/libnss_gns.so.2} exists on
1503 your system, it should have been created during the installation.
1504
1505
1506 @c **********************************************************************
1507 @cindex TESTING library
1508 @node TESTING library
1509 @section TESTING library
1510
1511 The TESTING library is used for writing testcases which involve starting a
1512 single or multiple peers. While peers can also be started by testcases
1513 using the ARM subsystem, using TESTING library provides an elegant way to
1514 do this. The configurations of the peers are auto-generated from a given
1515 template to have non-conflicting port numbers ensuring that peers'
1516 services do not run into bind errors. This is achieved by testing ports'
1517 availability by binding a listening socket to them before allocating them
1518 to services in the generated configurations.
1519
1520 An another advantage while using TESTING is that it shortens the testcase
1521 startup time as the hostkeys for peers are copied from a pre-computed set
1522 of hostkeys instead of generating them at peer startup which may take a
1523 considerable amount of time when starting multiple peers or on an embedded
1524 processor.
1525
1526 TESTING also allows for certain services to be shared among peers. This
1527 feature is invaluable when testing with multiple peers as it helps to
1528 reduce the number of services run per each peer and hence the total
1529 number of processes run per testcase.
1530
1531 TESTING library only handles creating, starting and stopping peers.
1532 Features useful for testcases such as connecting peers in a topology are
1533 not available in TESTING but are available in the TESTBED subsystem.
1534 Furthermore, TESTING only creates peers on the localhost, however by
1535 using TESTBED testcases can benefit from creating peers across multiple
1536 hosts.
1537
1538 @menu
1539 * API::
1540 * Finer control over peer stop::
1541 * Helper functions::
1542 * Testing with multiple processes::
1543 @end menu
1544
1545 @cindex TESTING API
1546 @node API
1547 @subsection API
1548
1549 TESTING abstracts a group of peers as a TESTING system. All peers in a
1550 system have common hostname and no two services of these peers have a
1551 same port or a UNIX domain socket path.
1552
1553 TESTING system can be created with the function
1554 @code{GNUNET_TESTING_system_create()} which returns a handle to the
1555 system. This function takes a directory path which is used for generating
1556 the configurations of peers, an IP address from which connections to the
1557 peers' services should be allowed, the hostname to be used in peers'
1558 configuration, and an array of shared service specifications of type
1559 @code{struct GNUNET_TESTING_SharedService}.
1560
1561 The shared service specification must specify the name of the service to
1562 share, the configuration pertaining to that shared service and the
1563 maximum number of peers that are allowed to share a single instance of
1564 the shared service.
1565
1566 TESTING system created with @code{GNUNET_TESTING_system_create()} chooses
1567 ports from the default range @code{12000} - @code{56000} while
1568 auto-generating configurations for peers.
1569 This range can be customised with the function
1570 @code{GNUNET_TESTING_system_create_with_portrange()}. This function is
1571 similar to @code{GNUNET_TESTING_system_create()} except that it take 2
1572 additional parameters --- the start and end of the port range to use.
1573
1574 A TESTING system is destroyed with the function
1575 @code{GNUNET_TESTING_system_destory()}. This function takes the handle of
1576 the system and a flag to remove the files created in the directory used
1577 to generate configurations.
1578
1579 A peer is created with the function
1580 @code{GNUNET_TESTING_peer_configure()}. This functions takes the system
1581 handle, a configuration template from which the configuration for the peer
1582 is auto-generated and the index from where the hostkey for the peer has to
1583 be copied from. When successful, this function returns a handle to the
1584 peer which can be used to start and stop it and to obtain the identity of
1585 the peer. If unsuccessful, a NULL pointer is returned with an error
1586 message. This function handles the generated configuration to have
1587 non-conflicting ports and paths.
1588
1589 Peers can be started and stopped by calling the functions
1590 @code{GNUNET_TESTING_peer_start()} and @code{GNUNET_TESTING_peer_stop()}
1591 respectively. A peer can be destroyed by calling the function
1592 @code{GNUNET_TESTING_peer_destroy}. When a peer is destroyed, the ports
1593 and paths in allocated in its configuration are reclaimed for usage in new
1594 peers.
1595
1596 @c ***********************************************************************
1597 @node Finer control over peer stop
1598 @subsection Finer control over peer stop
1599
1600 Using @code{GNUNET_TESTING_peer_stop()} is normally fine for testcases.
1601 However, calling this function for each peer is inefficient when trying to
1602 shutdown multiple peers as this function sends the termination signal to
1603 the given peer process and waits for it to terminate. It would be faster
1604 in this case to send the termination signals to the peers first and then
1605 wait on them. This is accomplished by the functions
1606 @code{GNUNET_TESTING_peer_kill()} which sends a termination signal to the
1607 peer, and the function @code{GNUNET_TESTING_peer_wait()} which waits on
1608 the peer.
1609
1610 Further finer control can be achieved by choosing to stop a peer
1611 asynchronously with the function @code{GNUNET_TESTING_peer_stop_async()}.
1612 This function takes a callback parameter and a closure for it in addition
1613 to the handle to the peer to stop. The callback function is called with
1614 the given closure when the peer is stopped. Using this function
1615 eliminates blocking while waiting for the peer to terminate.
1616
1617 An asynchronous peer stop can be canceled by calling the function
1618 @code{GNUNET_TESTING_peer_stop_async_cancel()}. Note that calling this
1619 function does not prevent the peer from terminating if the termination
1620 signal has already been sent to it. It does, however, cancels the
1621 callback to be called when the peer is stopped.
1622
1623 @c ***********************************************************************
1624 @node Helper functions
1625 @subsection Helper functions
1626
1627 Most of the testcases can benefit from an abstraction which configures a
1628 peer and starts it. This is provided by the function
1629 @code{GNUNET_TESTING_peer_run()}. This function takes the testing
1630 directory pathname, a configuration template, a callback and its closure.
1631 This function creates a peer in the given testing directory by using the
1632 configuration template, starts the peer and calls the given callback with
1633 the given closure.
1634
1635 The function @code{GNUNET_TESTING_peer_run()} starts the ARM service of
1636 the peer which starts the rest of the configured services. A similar
1637 function @code{GNUNET_TESTING_service_run} can be used to just start a
1638 single service of a peer. In this case, the peer's ARM service is not
1639 started; instead, only the given service is run.
1640
1641 @c ***********************************************************************
1642 @node Testing with multiple processes
1643 @subsection Testing with multiple processes
1644
1645 When testing GNUnet, the splitting of the code into a services and clients
1646 often complicates testing. The solution to this is to have the testcase
1647 fork @code{gnunet-service-arm}, ask it to start the required server and
1648 daemon processes and then execute appropriate client actions (to test the
1649 client APIs or the core module or both). If necessary, multiple ARM
1650 services can be forked using different ports (!) to simulate a network.
1651 However, most of the time only one ARM process is needed. Note that on
1652 exit, the testcase should shutdown ARM with a @code{TERM} signal (to give
1653 it the chance to cleanly stop its child processes).
1654
1655 The following code illustrates spawning and killing an ARM process from a
1656 testcase:
1657
1658 @example
1659 static void run (void *cls,
1660                  char *const *args,
1661                  const char *cfgfile,
1662                  const struct GNUNET_CONFIGURATION_Handle *cfg) @{
1663   struct GNUNET_OS_Process *arm_pid;
1664   arm_pid = GNUNET_OS_start_process (NULL,
1665                                      NULL,
1666                                      "gnunet-service-arm",
1667                                      "gnunet-service-arm",
1668                                      "-c",
1669                                      cfgname,
1670                                      NULL);
1671   /* do real test work here */
1672   if (0 != GNUNET_OS_process_kill (arm_pid, SIGTERM))
1673     GNUNET_log_strerror
1674       (GNUNET_ERROR_TYPE_WARNING, "kill");
1675   GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (arm_pid));
1676   GNUNET_OS_process_close (arm_pid); @}
1677
1678 GNUNET_PROGRAM_run (argc, argv,
1679                     "NAME-OF-TEST",
1680                     "nohelp",
1681                     options,
1682                     &run,
1683                     cls);
1684 @end example
1685
1686
1687 An alternative way that works well to test plugins is to implement a
1688 mock-version of the environment that the plugin expects and then to
1689 simply load the plugin directly.
1690
1691 @c ***********************************************************************
1692 @node Performance regression analysis with Gauger
1693 @section Performance regression analysis with Gauger
1694
1695 To help avoid performance regressions, GNUnet uses Gauger. Gauger is a
1696 simple logging tool that allows remote hosts to send performance data to
1697 a central server, where this data can be analyzed and visualized. Gauger
1698 shows graphs of the repository revisions and the performance data recorded
1699 for each revision, so sudden performance peaks or drops can be identified
1700 and linked to a specific revision number.
1701
1702 In the case of GNUnet, the buildbots log the performance data obtained
1703 during the tests after each build. The data can be accessed on GNUnet's
1704 Gauger page.
1705
1706 The menu on the left allows to select either the results of just one
1707 build bot (under "Hosts") or review the data from all hosts for a given
1708 test result (under "Metrics"). In case of very different absolute value
1709 of the results, for instance arm vs. amd64 machines, the option
1710 "Normalize" on a metric view can help to get an idea about the
1711 performance evolution across all hosts.
1712
1713 Using Gauger in GNUnet and having the performance of a module tracked over
1714 time is very easy. First of course, the testcase must generate some
1715 consistent metric, which makes sense to have logged. Highly volatile or
1716 random dependent metrics probably are not ideal candidates for meaningful
1717 regression detection.
1718
1719 To start logging any value, just include @code{gauger.h} in your testcase
1720 code. Then, use the macro @code{GAUGER()} to make the Buildbots log
1721 whatever value is of interest for you to @code{gnunet.org}'s Gauger
1722 server. No setup is necessary as most Buildbots have already everything
1723 in place and new metrics are created on demand. To delete a metric, you
1724 need to contact a member of the GNUnet development team (a file will need
1725 to be removed manually from the respective directory).
1726
1727 The code in the test should look like this:
1728
1729 @example
1730 [other includes]
1731 #include <gauger.h>
1732
1733 int main (int argc, char *argv[]) @{
1734
1735   [run test, generate data]
1736     GAUGER("YOUR_MODULE",
1737            "METRIC_NAME",
1738            (float)value,
1739            "UNIT"); @}
1740 @end example
1741
1742 Where:
1743
1744 @table @asis
1745
1746 @item @strong{YOUR_MODULE} is a category in the gauger page and should be
1747 the name of the module or subsystem like "Core" or "DHT"
1748 @item @strong{METRIC} is
1749 the name of the metric being collected and should be concise and
1750 descriptive, like "PUT operations in sqlite-datastore".
1751 @item @strong{value} is the value
1752 of the metric that is logged for this run.
1753 @item @strong{UNIT} is the unit in
1754 which the value is measured, for instance "kb/s" or "kb of RAM/node".
1755 @end table
1756
1757 If you wish to use Gauger for your own project, you can grab a copy of the
1758 latest stable release or check out Gauger's Subversion repository.
1759
1760 @cindex TESTBED Subsystem
1761 @node TESTBED Subsystem
1762 @section TESTBED Subsystem
1763
1764 The TESTBED subsystem facilitates testing and measuring of multi-peer
1765 deployments on a single host or over multiple hosts.
1766
1767 The architecture of the testbed module is divided into the following:
1768 @itemize @bullet
1769
1770 @item Testbed API: An API which is used by the testing driver programs. It
1771 provides with functions for creating, destroying, starting, stopping
1772 peers, etc.
1773
1774 @item Testbed service (controller): A service which is started through the
1775 Testbed API. This service handles operations to create, destroy, start,
1776 stop peers, connect them, modify their configurations.
1777
1778 @item Testbed helper: When a controller has to be started on a host, the
1779 testbed API starts the testbed helper on that host which in turn starts
1780 the controller. The testbed helper receives a configuration for the
1781 controller through its stdin and changes it to ensure the controller
1782 doesn't run into any port conflict on that host.
1783 @end itemize
1784
1785
1786 The testbed service (controller) is different from the other GNUnet
1787 services in that it is not started by ARM and is not supposed to be run
1788 as a daemon. It is started by the testbed API through a testbed helper.
1789 In a typical scenario involving multiple hosts, a controller is started
1790 on each host. Controllers take up the actual task of creating peers,
1791 starting and stopping them on the hosts they run.
1792
1793 While running deployments on a single localhost the testbed API starts the
1794 testbed helper directly as a child process. When running deployments on
1795 remote hosts the testbed API starts Testbed Helpers on each remote host
1796 through remote shell. By default testbed API uses SSH as a remote shell.
1797 This can be changed by setting the environmental variable
1798 GNUNET_TESTBED_RSH_CMD to the required remote shell program. This
1799 variable can also contain parameters which are to be passed to the remote
1800 shell program. For e.g:
1801
1802 @example
1803 export GNUNET_TESTBED_RSH_CMD="ssh -o BatchMode=yes \
1804 -o NoHostAuthenticationForLocalhost=yes %h"
1805 @end example
1806
1807 Substitutions are allowed in the command string above,
1808 this allows for substitutions through placemarks which begin with a `%'.
1809 At present the following substitutions are supported
1810
1811 @itemize @bullet
1812 @item %h: hostname
1813 @item %u: username
1814 @item %p: port
1815 @end itemize
1816
1817 Note that the substitution placemark is replaced only when the
1818 corresponding field is available and only once. Specifying
1819
1820 @example
1821 %u@@%h
1822 @end example
1823
1824 doesn't work either. If you want to user username substitutions for
1825 @command{SSH}, use the argument @code{-l} before the
1826 username substitution.
1827
1828 For example:
1829 @example
1830 ssh -l %u -p %p %h
1831 @end example
1832
1833 The testbed API and the helper communicate through the helpers stdin and
1834 stdout. As the helper is started through a remote shell on remote hosts
1835 any output messages from the remote shell interfere with the communication
1836 and results in a failure while starting the helper. For this reason, it is
1837 suggested to use flags to make the remote shells produce no output
1838 messages and to have password-less logins. The default remote shell, SSH,
1839 the default options are:
1840
1841 @example
1842 -o BatchMode=yes -o NoHostBasedAuthenticationForLocalhost=yes"
1843 @end example
1844
1845 Password-less logins should be ensured by using SSH keys.
1846
1847 Since the testbed API executes the remote shell as a non-interactive
1848 shell, certain scripts like .bashrc, .profiler may not be executed. If
1849 this is the case testbed API can be forced to execute an interactive
1850 shell by setting up the environmental variable
1851 @code{GNUNET_TESTBED_RSH_CMD_SUFFIX} to a shell program.
1852
1853 An example could be:
1854
1855 @example
1856 export GNUNET_TESTBED_RSH_CMD_SUFFIX="sh -lc"
1857 @end example
1858
1859 The testbed API will then execute the remote shell program as:
1860
1861 @example
1862 $GNUNET_TESTBED_RSH_CMD -p $port $dest $GNUNET_TESTBED_RSH_CMD_SUFFIX \
1863 gnunet-helper-testbed
1864 @end example
1865
1866 On some systems, problems may arise while starting testbed helpers if
1867 GNUnet is installed into a custom location since the helper may not be
1868 found in the standard path. This can be addressed by setting the variable
1869 `@code{HELPER_BINARY_PATH}' to the path of the testbed helper.
1870 Testbed API will then use this path to start helper binaries both
1871 locally and remotely.
1872
1873 Testbed API can accessed by including the
1874 @file{gnunet_testbed_service.h} file and linking with
1875 @code{-lgnunettestbed}.
1876
1877 @c ***********************************************************************
1878 @menu
1879 * Supported Topologies::
1880 * Hosts file format::
1881 * Topology file format::
1882 * Testbed Barriers::
1883 * TESTBED Caveats::
1884 @end menu
1885
1886 @node Supported Topologies
1887 @subsection Supported Topologies
1888
1889 While testing multi-peer deployments, it is often needed that the peers
1890 are connected in some topology. This requirement is addressed by the
1891 function @code{GNUNET_TESTBED_overlay_connect()} which connects any given
1892 two peers in the testbed.
1893
1894 The API also provides a helper function
1895 @code{GNUNET_TESTBED_overlay_configure_topology()} to connect a given set
1896 of peers in any of the following supported topologies:
1897
1898 @itemize @bullet
1899
1900 @item @code{GNUNET_TESTBED_TOPOLOGY_CLIQUE}: All peers are connected with
1901 each other
1902
1903 @item @code{GNUNET_TESTBED_TOPOLOGY_LINE}: Peers are connected to form a
1904 line
1905
1906 @item @code{GNUNET_TESTBED_TOPOLOGY_RING}: Peers are connected to form a
1907 ring topology
1908
1909 @item @code{GNUNET_TESTBED_TOPOLOGY_2D_TORUS}: Peers are connected to
1910 form a 2 dimensional torus topology. The number of peers may not be a
1911 perfect square, in that case the resulting torus may not have the uniform
1912 poloidal and toroidal lengths
1913
1914 @item @code{GNUNET_TESTBED_TOPOLOGY_ERDOS_RENYI}: Topology is generated
1915 to form a random graph. The number of links to be present should be given
1916
1917 @item @code{GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD}: Peers are connected to
1918 form a 2D Torus with some random links among them. The number of random
1919 links are to be given
1920
1921 @item @code{GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD_RING}: Peers are
1922 connected to form a ring with some random links among them. The number of
1923 random links are to be given
1924
1925 @item @code{GNUNET_TESTBED_TOPOLOGY_SCALE_FREE}: Connects peers in a
1926 topology where peer connectivity follows power law - new peers are
1927 connected with high probability to well connected peers.
1928 (See Emergence of Scaling in Random Networks. Science 286,
1929 509-512, 1999
1930 (@uref{https://git.gnunet.org/bibliography.git/plain/docs/emergence_of_scaling_in_random_networks__barabasi_albert_science_286__1999.pdf, pdf}))
1931
1932 @item @code{GNUNET_TESTBED_TOPOLOGY_FROM_FILE}: The topology information
1933 is loaded from a file. The path to the file has to be given.
1934 @xref{Topology file format}, for the format of this file.
1935
1936 @item @code{GNUNET_TESTBED_TOPOLOGY_NONE}: No topology
1937 @end itemize
1938
1939
1940 The above supported topologies can be specified respectively by setting
1941 the variable @code{OVERLAY_TOPOLOGY} to the following values in the
1942 configuration passed to Testbed API functions
1943 @code{GNUNET_TESTBED_test_run()} and
1944 @code{GNUNET_TESTBED_run()}:
1945
1946 @itemize @bullet
1947 @item @code{CLIQUE}
1948 @item @code{RING}
1949 @item @code{LINE}
1950 @item @code{2D_TORUS}
1951 @item @code{RANDOM}
1952 @item @code{SMALL_WORLD}
1953 @item @code{SMALL_WORLD_RING}
1954 @item @code{SCALE_FREE}
1955 @item @code{FROM_FILE}
1956 @item @code{NONE}
1957 @end itemize
1958
1959
1960 Topologies @code{RANDOM}, @code{SMALL_WORLD} and @code{SMALL_WORLD_RING}
1961 require the option @code{OVERLAY_RANDOM_LINKS} to be set to the number of
1962 random links to be generated in the configuration. The option will be
1963 ignored for the rest of the topologies.
1964
1965 Topology @code{SCALE_FREE} requires the options
1966 @code{SCALE_FREE_TOPOLOGY_CAP} to be set to the maximum number of peers
1967 which can connect to a peer and @code{SCALE_FREE_TOPOLOGY_M} to be set to
1968 how many peers a peer should be at least connected to.
1969
1970 Similarly, the topology @code{FROM_FILE} requires the option
1971 @code{OVERLAY_TOPOLOGY_FILE} to contain the path of the file containing
1972 the topology information. This option is ignored for the rest of the
1973 topologies. @xref{Topology file format}, for the format of this file.
1974
1975 @c ***********************************************************************
1976 @node Hosts file format
1977 @subsection Hosts file format
1978
1979 The testbed API offers the function
1980 @code{GNUNET_TESTBED_hosts_load_from_file()} to load from a given file
1981 details about the hosts which testbed can use for deploying peers.
1982 This function is useful to keep the data about hosts
1983 separate instead of hard coding them in code.
1984
1985 Another helper function from testbed API, @code{GNUNET_TESTBED_run()}
1986 also takes a hosts file name as its parameter. It uses the above
1987 function to populate the hosts data structures and start controllers to
1988 deploy peers.
1989
1990 These functions require the hosts file to be of the following format:
1991 @itemize @bullet
1992 @item Each line is interpreted to have details about a host
1993 @item Host details should include the username to use for logging into the
1994 host, the hostname of the host and the port number to use for the remote
1995 shell program. All thee values should be given.
1996 @item These details should be given in the following format:
1997 @example
1998 <username>@@<hostname>:<port>
1999 @end example
2000 @end itemize
2001
2002 Note that having canonical hostnames may cause problems while resolving
2003 the IP addresses (See this bug). Hence it is advised to provide the hosts'
2004 IP numerical addresses as hostnames whenever possible.
2005
2006 @c ***********************************************************************
2007 @node Topology file format
2008 @subsection Topology file format
2009
2010 A topology file describes how peers are to be connected. It should adhere
2011 to the following format for testbed to parse it correctly.
2012
2013 Each line should begin with the target peer id. This should be followed by
2014 a colon(`:') and origin peer ids separated by `|'. All spaces except for
2015 newline characters are ignored. The API will then try to connect each
2016 origin peer to the target peer.
2017
2018 For example, the following file will result in 5 overlay connections:
2019 [2->1], [3->1],[4->3], [0->3], [2->0]@
2020 @code{@ 1:2|3@ 3:4| 0@ 0: 2@ }
2021
2022 @c ***********************************************************************
2023 @node Testbed Barriers
2024 @subsection Testbed Barriers
2025
2026 The testbed subsystem's barriers API facilitates coordination among the
2027 peers run by the testbed and the experiment driver. The concept is
2028 similar to the barrier synchronisation mechanism found in parallel
2029 programming or multi-threading paradigms - a peer waits at a barrier upon
2030 reaching it until the barrier is reached by a predefined number of peers.
2031 This predefined number of peers required to cross a barrier is also called
2032 quorum. We say a peer has reached a barrier if the peer is waiting for the
2033 barrier to be crossed. Similarly a barrier is said to be reached if the
2034 required quorum of peers reach the barrier. A barrier which is reached is
2035 deemed as crossed after all the peers waiting on it are notified.
2036
2037 The barriers API provides the following functions:
2038 @itemize @bullet
2039 @item @strong{@code{GNUNET_TESTBED_barrier_init()}:} function to
2040 initialize a barrier in the experiment
2041 @item @strong{@code{GNUNET_TESTBED_barrier_cancel()}:} function to cancel
2042 a barrier which has been initialized before
2043 @item @strong{@code{GNUNET_TESTBED_barrier_wait()}:} function to signal
2044 barrier service that the caller has reached a barrier and is waiting for
2045 it to be crossed
2046 @item @strong{@code{GNUNET_TESTBED_barrier_wait_cancel()}:} function to
2047 stop waiting for a barrier to be crossed
2048 @end itemize
2049
2050
2051 Among the above functions, the first two, namely
2052 @code{GNUNET_TESTBED_barrier_init()} and
2053 @code{GNUNET_TESTBED_barrier_cancel()} are used by experiment drivers. All
2054 barriers should be initialised by the experiment driver by calling
2055 @code{GNUNET_TESTBED_barrier_init()}. This function takes a name to
2056 identify the barrier, the quorum required for the barrier to be crossed
2057 and a notification callback for notifying the experiment driver when the
2058 barrier is crossed. @code{GNUNET_TESTBED_barrier_cancel()} cancels an
2059 initialised barrier and frees the resources allocated for it. This
2060 function can be called upon a initialised barrier before it is crossed.
2061
2062 The remaining two functions @code{GNUNET_TESTBED_barrier_wait()} and
2063 @code{GNUNET_TESTBED_barrier_wait_cancel()} are used in the peer's
2064 processes. @code{GNUNET_TESTBED_barrier_wait()} connects to the local
2065 barrier service running on the same host the peer is running on and
2066 registers that the caller has reached the barrier and is waiting for the
2067 barrier to be crossed. Note that this function can only be used by peers
2068 which are started by testbed as this function tries to access the local
2069 barrier service which is part of the testbed controller service. Calling
2070 @code{GNUNET_TESTBED_barrier_wait()} on an uninitialised barrier results
2071 in failure. @code{GNUNET_TESTBED_barrier_wait_cancel()} cancels the
2072 notification registered by @code{GNUNET_TESTBED_barrier_wait()}.
2073
2074
2075 @c ***********************************************************************
2076 @menu
2077 * Implementation::
2078 @end menu
2079
2080 @node Implementation
2081 @subsubsection Implementation
2082
2083 Since barriers involve coordination between experiment driver and peers,
2084 the barrier service in the testbed controller is split into two
2085 components. The first component responds to the message generated by the
2086 barrier API used by the experiment driver (functions
2087 @code{GNUNET_TESTBED_barrier_init()} and
2088 @code{GNUNET_TESTBED_barrier_cancel()}) and the second component to the
2089 messages generated by barrier API used by peers (functions
2090 @code{GNUNET_TESTBED_barrier_wait()} and
2091 @code{GNUNET_TESTBED_barrier_wait_cancel()}).
2092
2093 Calling @code{GNUNET_TESTBED_barrier_init()} sends a
2094 @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_INIT} message to the master
2095 controller. The master controller then registers a barrier and calls
2096 @code{GNUNET_TESTBED_barrier_init()} for each its subcontrollers. In this
2097 way barrier initialisation is propagated to the controller hierarchy.
2098 While propagating initialisation, any errors at a subcontroller such as
2099 timeout during further propagation are reported up the hierarchy back to
2100 the experiment driver.
2101
2102 Similar to @code{GNUNET_TESTBED_barrier_init()},
2103 @code{GNUNET_TESTBED_barrier_cancel()} propagates
2104 @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_CANCEL} message which causes
2105 controllers to remove an initialised barrier.
2106
2107 The second component is implemented as a separate service in the binary
2108 `gnunet-service-testbed' which already has the testbed controller service.
2109 Although this deviates from the gnunet process architecture of having one
2110 service per binary, it is needed in this case as this component needs
2111 access to barrier data created by the first component. This component
2112 responds to @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_WAIT} messages from
2113 local peers when they call @code{GNUNET_TESTBED_barrier_wait()}. Upon
2114 receiving @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_WAIT} message, the
2115 service checks if the requested barrier has been initialised before and
2116 if it was not initialised, an error status is sent through
2117 @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_STATUS} message to the local
2118 peer and the connection from the peer is terminated. If the barrier is
2119 initialised before, the barrier's counter for reached peers is incremented
2120 and a notification is registered to notify the peer when the barrier is
2121 reached. The connection from the peer is left open.
2122
2123 When enough peers required to attain the quorum send
2124 @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_WAIT} messages, the controller
2125 sends a @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_STATUS} message to its
2126 parent informing that the barrier is crossed. If the controller has
2127 started further subcontrollers, it delays this message until it receives
2128 a similar notification from each of those subcontrollers. Finally, the
2129 barriers API at the experiment driver receives the
2130 @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_STATUS} when the barrier is
2131 reached at all the controllers.
2132
2133 The barriers API at the experiment driver responds to the
2134 @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_STATUS} message by echoing it
2135 back to the master controller and notifying the experiment controller
2136 through the notification callback that a barrier has been crossed. The
2137 echoed @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_STATUS} message is
2138 propagated by the master controller to the controller hierarchy. This
2139 propagation triggers the notifications registered by peers at each of the
2140 controllers in the hierarchy. Note the difference between this downward
2141 propagation of the @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_STATUS}
2142 message from its upward propagation --- the upward propagation is needed
2143 for ensuring that the barrier is reached by all the controllers and the
2144 downward propagation is for triggering that the barrier is crossed.
2145
2146 @cindex TESTBED Caveats
2147 @node TESTBED Caveats
2148 @subsection TESTBED Caveats
2149
2150 This section documents a few caveats when using the GNUnet testbed
2151 subsystem.
2152
2153 @c ***********************************************************************
2154 @menu
2155 * CORE must be started::
2156 * ATS must want the connections::
2157 @end menu
2158
2159 @node CORE must be started
2160 @subsubsection CORE must be started
2161
2162 A uncomplicated issue is bug #3993
2163 (@uref{https://bugs.gnunet.org/view.php?id=3993, https://bugs.gnunet.org/view.php?id=3993}):
2164 Your configuration MUST somehow ensure that for each peer the
2165 @code{CORE} service is started when the peer is setup, otherwise
2166 @code{TESTBED} may fail to connect peers when the topology is initialized,
2167 as @code{TESTBED} will start some @code{CORE} services but not
2168 necessarily all (but it relies on all of them running). The easiest way
2169 is to set
2170
2171 @example
2172 [core]
2173 IMMEDIATE_START = YES
2174 @end example
2175
2176 @noindent
2177 in the configuration file.
2178 Alternatively, having any service that directly or indirectly depends on
2179 @code{CORE} being started with @code{IMMEDIATE_START} will also do.
2180 This issue largely arises if users try to over-optimize by not
2181 starting any services with @code{IMMEDIATE_START}.
2182
2183 @c ***********************************************************************
2184 @node ATS must want the connections
2185 @subsubsection ATS must want the connections
2186
2187 When TESTBED sets up connections, it only offers the respective HELLO
2188 information to the TRANSPORT service. It is then up to the ATS service to
2189 @strong{decide} to use the connection. The ATS service will typically
2190 eagerly establish any connection if the number of total connections is
2191 low (relative to bandwidth). Details may further depend on the
2192 specific ATS backend that was configured. If ATS decides to NOT establish
2193 a connection (even though TESTBED provided the required information), then
2194 that connection will count as failed for TESTBED. Note that you can
2195 configure TESTBED to tolerate a certain number of connection failures
2196 (see '-e' option of gnunet-testbed-profiler). This issue largely arises
2197 for dense overlay topologies, especially if you try to create cliques
2198 with more than 20 peers.
2199
2200 @cindex libgnunetutil
2201 @node libgnunetutil
2202 @section libgnunetutil
2203
2204 libgnunetutil is the fundamental library that all GNUnet code builds upon.
2205 Ideally, this library should contain most of the platform dependent code
2206 (except for user interfaces and really special needs that only few
2207 applications have). It is also supposed to offer basic services that most
2208 if not all GNUnet binaries require. The code of libgnunetutil is in the
2209 @file{src/util/} directory. The public interface to the library is in the
2210 gnunet_util.h header. The functions provided by libgnunetutil fall
2211 roughly into the following categories (in roughly the order of importance
2212 for new developers):
2213
2214 @itemize @bullet
2215 @item logging (common_logging.c)
2216 @item memory allocation (common_allocation.c)
2217 @item endianess conversion (common_endian.c)
2218 @item internationalization (common_gettext.c)
2219 @item String manipulation (string.c)
2220 @item file access (disk.c)
2221 @item buffered disk IO (bio.c)
2222 @item time manipulation (time.c)
2223 @item configuration parsing (configuration.c)
2224 @item command-line handling (getopt*.c)
2225 @item cryptography (crypto_*.c)
2226 @item data structures (container_*.c)
2227 @item CPS-style scheduling (scheduler.c)
2228 @item Program initialization (program.c)
2229 @item Networking (network.c, client.c, server*.c, service.c)
2230 @item message queuing (mq.c)
2231 @item bandwidth calculations (bandwidth.c)
2232 @item Other OS-related (os*.c, plugin.c, signal.c)
2233 @item Pseudonym management (pseudonym.c)
2234 @end itemize
2235
2236 It should be noted that only developers that fully understand this entire
2237 API will be able to write good GNUnet code.
2238
2239 Ideally, porting GNUnet should only require porting the gnunetutil
2240 library. More testcases for the gnunetutil APIs are therefore a great
2241 way to make porting of GNUnet easier.
2242
2243 @menu
2244 * Logging::
2245 * Interprocess communication API (IPC)::
2246 * Cryptography API::
2247 * Message Queue API::
2248 * Service API::
2249 * Optimizing Memory Consumption of GNUnet's (Multi-) Hash Maps::
2250 * CONTAINER_MDLL API::
2251 @end menu
2252
2253 @cindex Logging
2254 @cindex log levels
2255 @node Logging
2256 @subsection Logging
2257
2258 GNUnet is able to log its activity, mostly for the purposes of debugging
2259 the program at various levels.
2260
2261 @file{gnunet_common.h} defines several @strong{log levels}:
2262 @table @asis
2263
2264 @item ERROR for errors
2265 (really problematic situations, often leading to crashes)
2266 @item WARNING for warnings
2267 (troubling situations that might have negative consequences, although
2268 not fatal)
2269 @item INFO for various information.
2270 Used somewhat rarely, as GNUnet statistics is used to hold and display
2271 most of the information that users might find interesting.
2272 @item DEBUG for debugging.
2273 Does not produce much output on normal builds, but when extra logging is
2274 enabled at compile time, a staggering amount of data is outputted under
2275 this log level.
2276 @end table
2277
2278
2279 Normal builds of GNUnet (configured with @code{--enable-logging[=yes]})
2280 are supposed to log nothing under DEBUG level. The
2281 @code{--enable-logging=verbose} configure option can be used to create a
2282 build with all logging enabled. However, such build will produce large
2283 amounts of log data, which is inconvenient when one tries to hunt down a
2284 specific problem.
2285
2286 To mitigate this problem, GNUnet provides facilities to apply a filter to
2287 reduce the logs:
2288 @table @asis
2289
2290 @item Logging by default When no log levels are configured in any other
2291 way (see below), GNUnet will default to the WARNING log level. This
2292 mostly applies to GNUnet command line utilities, services and daemons;
2293 tests will always set log level to WARNING or, if
2294 @code{--enable-logging=verbose} was passed to configure, to DEBUG. The
2295 default level is suggested for normal operation.
2296 @item The -L option Most GNUnet executables accept an "-L loglevel" or
2297 "--log=loglevel" option. If used, it makes the process set a global log
2298 level to "loglevel". Thus it is possible to run some processes
2299 with -L DEBUG, for example, and others with -L ERROR to enable specific
2300 settings to diagnose problems with a particular process.
2301 @item Configuration files.  Because GNUnet
2302 service and daemon processes are usually launched by gnunet-arm, it is not
2303 possible to pass different custom command line options directly to every
2304 one of them. The options passed to @code{gnunet-arm} only affect
2305 gnunet-arm and not the rest of GNUnet. However, one can specify a
2306 configuration key "OPTIONS" in the section that corresponds to a service
2307 or a daemon, and put a value of "-L loglevel" there. This will make the
2308 respective service or daemon set its log level to "loglevel" (as the
2309 value of OPTIONS will be passed as a command-line argument).
2310
2311 To specify the same log level for all services without creating separate
2312 "OPTIONS" entries in the configuration for each one, the user can specify
2313 a config key "GLOBAL_POSTFIX" in the [arm] section of the configuration
2314 file. The value of GLOBAL_POSTFIX will be appended to all command lines
2315 used by the ARM service to run other services. It can contain any option
2316 valid for all GNUnet commands, thus in particular the "-L loglevel"
2317 option. The ARM service itself is, however, unaffected by GLOBAL_POSTFIX;
2318 to set log level for it, one has to specify "OPTIONS" key in the [arm]
2319 section.
2320 @item Environment variables.
2321 Setting global per-process log levels with "-L loglevel" does not offer
2322 sufficient log filtering granularity, as one service will call interface
2323 libraries and supporting libraries of other GNUnet services, potentially
2324 producing lots of debug log messages from these libraries. Also, changing
2325 the config file is not always convenient (especially when running the
2326 GNUnet test suite).@ To fix that, and to allow GNUnet to use different
2327 log filtering at runtime without re-compiling the whole source tree, the
2328 log calls were changed to be configurable at run time. To configure them
2329 one has to define environment variables "GNUNET_FORCE_LOGFILE",
2330 "GNUNET_LOG" and/or "GNUNET_FORCE_LOG":
2331 @itemize @bullet
2332
2333 @item "GNUNET_LOG" only affects the logging when no global log level is
2334 configured by any other means (that is, the process does not explicitly
2335 set its own log level, there are no "-L loglevel" options on command line
2336 or in configuration files), and can be used to override the default
2337 WARNING log level.
2338
2339 @item "GNUNET_FORCE_LOG" will completely override any other log
2340 configuration options given.
2341
2342 @item "GNUNET_FORCE_LOGFILE" will completely override the location of the
2343 file to log messages to. It should contain a relative or absolute file
2344 name. Setting GNUNET_FORCE_LOGFILE is equivalent to passing
2345 "--log-file=logfile" or "-l logfile" option (see below). It supports "[]"
2346 format in file names, but not "@{@}" (see below).
2347 @end itemize
2348
2349
2350 Because environment variables are inherited by child processes when they
2351 are launched, starting or re-starting the ARM service with these
2352 variables will propagate them to all other services.
2353
2354 "GNUNET_LOG" and "GNUNET_FORCE_LOG" variables must contain a specially
2355 formatted @strong{logging definition} string, which looks like this:@
2356
2357 @c FIXME: Can we close this with [/component] instead?
2358 @example
2359 [component];[file];[function];[from_line[-to_line]];loglevel[/component...]
2360 @end example
2361
2362 That is, a logging definition consists of definition entries, separated by
2363 slashes ('/'). If only one entry is present, there is no need to add a
2364 slash to its end (although it is not forbidden either).@ All definition
2365 fields (component, file, function, lines and loglevel) are mandatory, but
2366 (except for the loglevel) they can be empty. An empty field means
2367 "match anything". Note that even if fields are empty, the semicolon (';')
2368 separators must be present.@ The loglevel field is mandatory, and must
2369 contain one of the log level names (ERROR, WARNING, INFO or DEBUG).@
2370 The lines field might contain one non-negative number, in which case it
2371 matches only one line, or a range "from_line-to_line", in which case it
2372 matches any line in the interval [from_line;to_line] (that is, including
2373 both start and end line).@ GNUnet mostly defaults component name to the
2374 name of the service that is implemented in a process ('transport',
2375 'core', 'peerinfo', etc), but logging calls can specify custom component
2376 names using @code{GNUNET_log_from}.@ File name and function name are
2377 provided by the compiler (__FILE__ and __FUNCTION__ built-ins).
2378
2379 Component, file and function fields are interpreted as non-extended
2380 regular expressions (GNU libc regex functions are used). Matching is
2381 case-sensitive, "^" and "$" will match the beginning and the end of the
2382 text. If a field is empty, its contents are automatically replaced with
2383 a ".*" regular expression, which matches anything. Matching is done in
2384 the default way, which means that the expression matches as long as it's
2385 contained anywhere in the string. Thus "GNUNET_" will match both
2386 "GNUNET_foo" and "BAR_GNUNET_BAZ". Use '^' and/or '$' to make sure that
2387 the expression matches at the start and/or at the end of the string.
2388 The semicolon (';') can't be escaped, and GNUnet will not use it in
2389 component names (it can't be used in function names and file names
2390 anyway).
2391
2392 @end table
2393
2394
2395 Every logging call in GNUnet code will be (at run time) matched against
2396 the log definitions passed to the process. If a log definition fields are
2397 matching the call arguments, then the call log level is compared the the
2398 log level of that definition. If the call log level is less or equal to
2399 the definition log level, the call is allowed to proceed. Otherwise the
2400 logging call is forbidden, and nothing is logged. If no definitions
2401 matched at all, GNUnet will use the global log level or (if a global log
2402 level is not specified) will default to WARNING (that is, it will allow
2403 the call to proceed, if its level is less or equal to the global log
2404 level or to WARNING).
2405
2406 That is, definitions are evaluated from left to right, and the first
2407 matching definition is used to allow or deny the logging call. Thus it is
2408 advised to place narrow definitions at the beginning of the logdef
2409 string, and generic definitions - at the end.
2410
2411 Whether a call is allowed or not is only decided the first time this
2412 particular call is made. The evaluation result is then cached, so that
2413 any attempts to make the same call later will be allowed or disallowed
2414 right away. Because of that runtime log level evaluation should not
2415 significantly affect the process performance.
2416 Log definition parsing is only done once, at the first call to
2417 @code{GNUNET_log_setup ()} made by the process (which is usually done soon after
2418 it starts).
2419
2420 At the moment of writing there is no way to specify logging definitions
2421 from configuration files, only via environment variables.
2422
2423 At the moment GNUnet will stop processing a log definition when it
2424 encounters an error in definition formatting or an error in regular
2425 expression syntax, and will not report the failure in any way.
2426
2427
2428 @c ***********************************************************************
2429 @menu
2430 * Examples::
2431 * Log files::
2432 * Updated behavior of GNUNET_log::
2433 @end menu
2434
2435 @node Examples
2436 @subsubsection Examples
2437
2438 @table @asis
2439
2440 @item @code{GNUNET_FORCE_LOG=";;;;DEBUG" gnunet-arm -s} Start GNUnet
2441 process tree, running all processes with DEBUG level (one should be
2442 careful with it, as log files will grow at alarming rate!)
2443 @item @code{GNUNET_FORCE_LOG="core;;;;DEBUG" gnunet-arm -s} Start GNUnet
2444 process tree, running the core service under DEBUG level (everything else
2445 will use configured or default level).
2446
2447 @item Start GNUnet process tree, allowing any logging calls from
2448 gnunet-service-transport_validation.c (everything else will use
2449 configured or default level).
2450
2451 @example
2452 GNUNET_FORCE_LOG=";gnunet-service-transport_validation.c;;; DEBUG" \
2453 gnunet-arm -s
2454 @end example
2455
2456 @item Start GNUnet process tree, allowing any logging calls from
2457 gnunet-gnunet-service-fs_push.c (everything else will use configured or
2458 default level).
2459
2460 @example
2461 GNUNET_FORCE_LOG="fs;gnunet-service-fs_push.c;;;DEBUG" gnunet-arm -s
2462 @end example
2463
2464 @item Start GNUnet process tree, allowing any logging calls from the
2465 GNUNET_NETWORK_socket_select function (everything else will use
2466 configured or default level).
2467
2468 @example
2469 GNUNET_FORCE_LOG=";;GNUNET_NETWORK_socket_select;;DEBUG" gnunet-arm -s
2470 @end example
2471
2472 @item Start GNUnet process tree, allowing any logging calls from the
2473 components that have "transport" in their names, and are made from
2474 function that have "send" in their names. Everything else will be allowed
2475 to be logged only if it has WARNING level.
2476
2477 @example
2478 GNUNET_FORCE_LOG="transport.*;;.*send.*;;DEBUG/;;;;WARNING" gnunet-arm -s
2479 @end example
2480
2481 @end table
2482
2483
2484 On Windows, one can use batch files to run GNUnet processes with special
2485 environment variables, without affecting the whole system. Such batch
2486 file will look like this:
2487
2488 @example
2489 set GNUNET_FORCE_LOG=;;do_transmit;;DEBUG@ gnunet-arm -s
2490 @end example
2491
2492 (note the absence of double quotes in the environment variable definition,
2493 as opposed to earlier examples, which use the shell).
2494 Another limitation, on Windows, GNUNET_FORCE_LOGFILE @strong{MUST} be set
2495 in order to GNUNET_FORCE_LOG to work.
2496
2497
2498 @cindex Log files
2499 @node Log files
2500 @subsubsection Log files
2501
2502 GNUnet can be told to log everything into a file instead of stderr (which
2503 is the default) using the "--log-file=logfile" or "-l logfile" option.
2504 This option can also be passed via command line, or from the "OPTION" and
2505 "GLOBAL_POSTFIX" configuration keys (see above). The file name passed
2506 with this option is subject to GNUnet filename expansion. If specified in
2507 "GLOBAL_POSTFIX", it is also subject to ARM service filename expansion,
2508 in particular, it may contain "@{@}" (left and right curly brace)
2509 sequence, which will be replaced by ARM with the name of the service.
2510 This is used to keep logs from more than one service separate, while only
2511 specifying one template containing "@{@}" in GLOBAL_POSTFIX.
2512
2513 As part of a secondary file name expansion, the first occurrence of "[]"
2514 sequence ("left square brace" followed by "right square brace") in the
2515 file name will be replaced with a process identifier or the process when
2516 it initializes its logging subsystem. As a result, all processes will log
2517 into different files. This is convenient for isolating messages of a
2518 particular process, and prevents I/O races when multiple processes try to
2519 write into the file at the same time. This expansion is done
2520 independently of "@{@}" expansion that ARM service does (see above).
2521
2522 The log file name that is specified via "-l" can contain format characters
2523 from the 'strftime' function family. For example, "%Y" will be replaced
2524 with the current year. Using "basename-%Y-%m-%d.log" would include the
2525 current year, month and day in the log file. If a GNUnet process runs for
2526 long enough to need more than one log file, it will eventually clean up
2527 old log files. Currently, only the last three log files (plus the current
2528 log file) are preserved. So once the fifth log file goes into use (so
2529 after 4 days if you use "%Y-%m-%d" as above), the first log file will be
2530 automatically deleted. Note that if your log file name only contains "%Y",
2531 then log files would be kept for 4 years and the logs from the first year
2532 would be deleted once year 5 begins. If you do not use any date-related
2533 string format codes, logs would never be automatically deleted by GNUnet.
2534
2535
2536 @c ***********************************************************************
2537
2538 @node Updated behavior of GNUNET_log
2539 @subsubsection Updated behavior of GNUNET_log
2540
2541 It's currently quite common to see constructions like this all over the
2542 code:
2543
2544 @example
2545 #if MESH_DEBUG
2546 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
2547 #endif
2548 @end example
2549
2550 The reason for the #if is not to avoid displaying the message when
2551 disabled (GNUNET_ERROR_TYPE takes care of that), but to avoid the
2552 compiler including it in the binary at all, when compiling GNUnet for
2553 platforms with restricted storage space / memory (MIPS routers,
2554 ARM plug computers / dev boards, etc).
2555
2556 This presents several problems: the code gets ugly, hard to write and it
2557 is very easy to forget to include the #if guards, creating non-consistent
2558 code. A new change in GNUNET_log aims to solve these problems.
2559
2560 @strong{This change requires to @file{./configure} with at least
2561 @code{--enable-logging=verbose} to see debug messages.}
2562
2563 Here is an example of code with dense debug statements:
2564
2565 @example
2566 switch (restrict_topology) @{
2567 case GNUNET_TESTING_TOPOLOGY_CLIQUE:#if VERBOSE_TESTING
2568 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Blacklisting all but clique
2569 topology\n")); #endif unblacklisted_connections = create_clique (pg,
2570 &remove_connections, BLACKLIST, GNUNET_NO); break; case
2571 GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING: #if VERBOSE_TESTING GNUNET_log
2572 (GNUNET_ERROR_TYPE_DEBUG, _("Blacklisting all but small world (ring)
2573 topology\n")); #endif unblacklisted_connections = create_small_world_ring
2574 (pg,&remove_connections, BLACKLIST); break;
2575 @end example
2576
2577
2578 Pretty hard to follow, huh?
2579
2580 From now on, it is not necessary to include the #if / #endif statements to
2581 achieve the same behavior. The @code{GNUNET_log} and @code{GNUNET_log_from}
2582 macros take
2583 care of it for you, depending on the configure option:
2584
2585 @itemize @bullet
2586 @item If @code{--enable-logging} is set to @code{no}, the binary will
2587 contain no log messages at all.
2588 @item If @code{--enable-logging} is set to @code{yes}, the binary will
2589 contain no DEBUG messages, and therefore running with @command{-L DEBUG}
2590 will have
2591 no effect. Other messages (ERROR, WARNING, INFO, etc) will be included.
2592 @item If @code{--enable-logging} is set to @code{verbose}, or
2593 @code{veryverbose} the binary will contain DEBUG messages (still, it will
2594 be necessary to run with @command{-L DEBUG} or set the DEBUG config option
2595 to show
2596 them).
2597 @end itemize
2598
2599
2600 If you are a developer:
2601 @itemize @bullet
2602 @item please make sure that you @code{./configure
2603 --enable-logging=@{verbose,veryverbose@}}, so you can see DEBUG messages.
2604 @item please remove the @code{#if} statements around @code{GNUNET_log
2605 (GNUNET_ERROR_TYPE_DEBUG, ...)} lines, to improve the readability of your
2606 code.
2607 @end itemize
2608
2609 Since now activating DEBUG automatically makes it VERBOSE and activates
2610 @strong{all} debug messages by default, you probably want to use the
2611 @uref{https://old.gnunet.org/logging, https://old.gnunet.org/logging}
2612 functionality to filter only relevant messages.
2613 A suitable configuration could be:
2614
2615 @example
2616 $ export GNUNET_FORCE_LOG="^YOUR_SUBSYSTEM$;;;;DEBUG/;;;;WARNING"
2617 @end example
2618
2619 Which will behave almost like enabling DEBUG in that subsystem before the
2620 change. Of course you can adapt it to your particular needs, this is only
2621 a quick example.
2622
2623 @cindex Interprocess communication API
2624 @cindex ICP
2625 @node Interprocess communication API (IPC)
2626 @subsection Interprocess communication API (IPC)
2627
2628 In GNUnet a variety of new message types might be defined and used in
2629 interprocess communication, in this tutorial we use the
2630 @code{struct AddressLookupMessage} as a example to introduce how to
2631 construct our own message type in GNUnet and how to implement the message
2632 communication between service and client.
2633 (Here, a client uses the @code{struct AddressLookupMessage} as a request
2634 to ask the server to return the address of any other peer connecting to
2635 the service.)
2636
2637
2638 @c ***********************************************************************
2639 @menu
2640 * Define new message types::
2641 * Define message struct::
2642 * Client - Establish connection::
2643 * Client - Initialize request message::
2644 * Client - Send request and receive response::
2645 * Server - Startup service::
2646 * Server - Add new handles for specified messages::
2647 * Server - Process request message::
2648 * Server - Response to client::
2649 * Server - Notification of clients::
2650 * Conversion between Network Byte Order (Big Endian) and Host Byte Order::
2651 @end menu
2652
2653 @node Define new message types
2654 @subsubsection Define new message types
2655
2656 First of all, you should define the new message type in
2657 @file{gnunet_protocols.h}:
2658
2659 @example
2660  // Request to look addresses of peers in server.
2661 #define GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP 29
2662   // Response to the address lookup request.
2663 #define GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY 30
2664 @end example
2665
2666 @c ***********************************************************************
2667 @node Define message struct
2668 @subsubsection Define message struct
2669
2670 After the type definition, the specified message structure should also be
2671 described in the header file, e.g. transport.h in our case.
2672
2673 @example
2674 struct AddressLookupMessage @{
2675   struct GNUNET_MessageHeader header;
2676   int32_t numeric_only GNUNET_PACKED;
2677   struct GNUNET_TIME_AbsoluteNBO timeout;
2678   uint32_t addrlen GNUNET_PACKED;
2679   /* followed by 'addrlen' bytes of the actual address, then
2680      followed by the 0-terminated name of the transport */ @};
2681 GNUNET_NETWORK_STRUCT_END
2682 @end example
2683
2684
2685 Please note @code{GNUNET_NETWORK_STRUCT_BEGIN} and @code{GNUNET_PACKED}
2686 which both ensure correct alignment when sending structs over the network.
2687
2688 @menu
2689 @end menu
2690
2691 @c ***********************************************************************
2692 @node Client - Establish connection
2693 @subsubsection Client - Establish connection
2694
2695
2696
2697 At first, on the client side, the underlying API is employed to create a
2698 new connection to a service, in our example the transport service would be
2699 connected.
2700
2701 @example
2702 struct GNUNET_CLIENT_Connection *client;
2703 client = GNUNET_CLIENT_connect ("transport", cfg);
2704 @end example
2705
2706 @c ***********************************************************************
2707 @node Client - Initialize request message
2708 @subsubsection Client - Initialize request message
2709
2710
2711 When the connection is ready, we initialize the message. In this step,
2712 all the fields of the message should be properly initialized, namely the
2713 size, type, and some extra user-defined data, such as timeout, name of
2714 transport, address and name of transport.
2715
2716 @example
2717 struct AddressLookupMessage *msg;
2718 size_t len = sizeof (struct AddressLookupMessage)
2719   + addressLen
2720   + strlen (nameTrans)
2721   + 1;
2722 msg->header->size = htons (len);
2723 msg->header->type = htons
2724 (GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP);
2725 msg->timeout = GNUNET_TIME_absolute_hton (abs_timeout);
2726 msg->addrlen = htonl (addressLen);
2727 char *addrbuf = (char *) &msg[1];
2728 memcpy (addrbuf, address, addressLen);
2729 char *tbuf = &addrbuf[addressLen];
2730 memcpy (tbuf, nameTrans, strlen (nameTrans) + 1);
2731 @end example
2732
2733 Note that, here the functions @code{htonl}, @code{htons} and
2734 @code{GNUNET_TIME_absolute_hton} are applied to convert little endian
2735 into big endian, about the usage of the big/small endian order and the
2736 corresponding conversion function please refer to Introduction of
2737 Big Endian and Little Endian.
2738
2739 @c ***********************************************************************
2740 @node Client - Send request and receive response
2741 @subsubsection Client - Send request and receive response
2742
2743
2744 @b{FIXME: This is very outdated, see the tutorial for the current API!}
2745
2746 Next, the client would send the constructed message as a request to the
2747 service and wait for the response from the service. To accomplish this
2748 goal, there are a number of API calls that can be used. In this example,
2749 @code{GNUNET_CLIENT_transmit_and_get_response} is chosen as the most
2750 appropriate function to use.
2751
2752 @example
2753 GNUNET_CLIENT_transmit_and_get_response
2754 (client, msg->header, timeout, GNUNET_YES, &address_response_processor,
2755 arp_ctx);
2756 @end example
2757
2758 the argument @code{address_response_processor} is a function with
2759 @code{GNUNET_CLIENT_MessageHandler} type, which is used to process the
2760 reply message from the service.
2761
2762 @node Server - Startup service
2763 @subsubsection Server - Startup service
2764
2765 After receiving the request message, we run a standard GNUnet service
2766 startup sequence using @code{GNUNET_SERVICE_run}, as follows,
2767
2768 @example
2769 int main(int argc, char**argv) @{
2770   GNUNET_SERVICE_run(argc, argv, "transport"
2771   GNUNET_SERVICE_OPTION_NONE, &run, NULL)); @}
2772 @end example
2773
2774 @c ***********************************************************************
2775 @node Server - Add new handles for specified messages
2776 @subsubsection Server - Add new handles for specified messages
2777
2778
2779 in the function above the argument @code{run} is used to initiate
2780 transport service,and defined like this:
2781
2782 @example
2783 static void run (void *cls,
2784 struct GNUNET_SERVER_Handle *serv,
2785 const struct GNUNET_CONFIGURATION_Handle *cfg) @{
2786   GNUNET_SERVER_add_handlers (serv, handlers); @}
2787 @end example
2788
2789
2790 Here, @code{GNUNET_SERVER_add_handlers} must be called in the run
2791 function to add new handlers in the service. The parameter
2792 @code{handlers} is a list of @code{struct GNUNET_SERVER_MessageHandler}
2793 to tell the service which function should be called when a particular
2794 type of message is received, and should be defined in this way:
2795
2796 @example
2797 static struct GNUNET_SERVER_MessageHandler handlers[] = @{
2798   @{&handle_start,
2799    NULL,
2800    GNUNET_MESSAGE_TYPE_TRANSPORT_START,
2801    0@},
2802   @{&handle_send,
2803    NULL,
2804    GNUNET_MESSAGE_TYPE_TRANSPORT_SEND,
2805    0@},
2806   @{&handle_try_connect,
2807    NULL,
2808    GNUNET_MESSAGE_TYPE_TRANSPORT_TRY_CONNECT,
2809    sizeof (struct TryConnectMessage)
2810   @},
2811   @{&handle_address_lookup,
2812    NULL,
2813    GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
2814    0@},
2815   @{NULL,
2816    NULL,
2817    0,
2818    0@}
2819 @};
2820 @end example
2821
2822
2823 As shown, the first member of the struct in the first area is a callback
2824 function, which is called to process the specified message types, given
2825 as the third member. The second parameter is the closure for the callback
2826 function, which is set to @code{NULL} in most cases, and the last
2827 parameter is the expected size of the message of this type, usually we
2828 set it to 0 to accept variable size, for special cases the exact size of
2829 the specified message also can be set. In addition, the terminator sign
2830 depicted as @code{@{NULL, NULL, 0, 0@}} is set in the last area.
2831
2832 @c ***********************************************************************
2833 @node Server - Process request message
2834 @subsubsection Server - Process request message
2835
2836
2837 After the initialization of transport service, the request message would
2838 be processed. Before handling the main message data, the validity of this
2839 message should be checked out, e.g., to check whether the size of message
2840 is correct.
2841
2842 @example
2843 size = ntohs (message->size);
2844 if (size < sizeof (struct AddressLookupMessage)) @{
2845   GNUNET_break_op (0);
2846   GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2847   return; @}
2848 @end example
2849
2850
2851 Note that, opposite to the construction method of the request message in
2852 the client, in the server the function @code{nothl} and @code{ntohs}
2853 should be employed during the extraction of the data from the message, so
2854 that the data in big endian order can be converted back into little
2855 endian order. See more in detail please refer to Introduction of
2856 Big Endian and Little Endian.
2857
2858 Moreover in this example, the name of the transport stored in the message
2859 is a 0-terminated string, so we should also check whether the name of the
2860 transport in the received message is 0-terminated:
2861
2862 @example
2863 nameTransport = (const char *) &address[addressLen];
2864 if (nameTransport[size - sizeof
2865                   (struct AddressLookupMessage)
2866                   - addressLen - 1] != '\0') @{
2867   GNUNET_break_op (0);
2868   GNUNET_SERVER_receive_done (client,
2869                               GNUNET_SYSERR);
2870   return; @}
2871 @end example
2872
2873 Here, @code{GNUNET_SERVER_receive_done} should be called to tell the
2874 service that the request is done and can receive the next message. The
2875 argument @code{GNUNET_SYSERR} here indicates that the service didn't
2876 understand the request message, and the processing of this request would
2877 be terminated.
2878
2879 In comparison to the aforementioned situation, when the argument is equal
2880 to @code{GNUNET_OK}, the service would continue to process the request
2881 message.
2882
2883 @c ***********************************************************************
2884 @node Server - Response to client
2885 @subsubsection Server - Response to client
2886
2887
2888 Once the processing of current request is done, the server should give the
2889 response to the client. A new @code{struct AddressLookupMessage} would be
2890 produced by the server in a similar way as the client did and sent to the
2891 client, but here the type should be
2892 @code{GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY} rather than
2893 @code{GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP} in client.
2894 @example
2895 struct AddressLookupMessage *msg;
2896 size_t len = sizeof (struct AddressLookupMessage)
2897   + addressLen
2898   + strlen (nameTrans) + 1;
2899 msg->header->size = htons (len);
2900 msg->header->type = htons
2901   (GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
2902
2903 // ...
2904
2905 struct GNUNET_SERVER_TransmitContext *tc;
2906 tc = GNUNET_SERVER_transmit_context_create (client);
2907 GNUNET_SERVER_transmit_context_append_data
2908 (tc,
2909  NULL,
2910  0,
2911  GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
2912 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
2913 @end example
2914
2915
2916 Note that, there are also a number of other APIs provided to the service
2917 to send the message.
2918
2919 @c ***********************************************************************
2920 @node Server - Notification of clients
2921 @subsubsection Server - Notification of clients
2922
2923
2924 Often a service needs to (repeatedly) transmit notifications to a client
2925 or a group of clients. In these cases, the client typically has once
2926 registered for a set of events and then needs to receive a message
2927 whenever such an event happens (until the client disconnects). The use of
2928 a notification context can help manage message queues to clients and
2929 handle disconnects. Notification contexts can be used to send
2930 individualized messages to a particular client or to broadcast messages
2931 to a group of clients. An individualized notification might look like
2932 this:
2933
2934 @example
2935 GNUNET_SERVER_notification_context_unicast(nc,
2936                                            client,
2937                                            msg,
2938                                            GNUNET_YES);
2939 @end example
2940
2941
2942 Note that after processing the original registration message for
2943 notifications, the server code still typically needs to call
2944 @code{GNUNET_SERVER_receive_done} so that the client can transmit further
2945 messages to the server.
2946
2947 @c ***********************************************************************
2948 @node Conversion between Network Byte Order (Big Endian) and Host Byte Order
2949 @subsubsection Conversion between Network Byte Order (Big Endian) and Host Byte Order
2950 @c %** subsub? it's a referenced page on the ipc document.
2951
2952
2953 Here we can simply comprehend big endian and little endian as Network Byte
2954 Order and Host Byte Order respectively. What is the difference between
2955 both two?
2956
2957 Usually in our host computer we store the data byte as Host Byte Order,
2958 for example, we store a integer in the RAM which might occupies 4 Byte,
2959 as Host Byte Order the higher Byte would be stored at the lower address
2960 of RAM, and the lower Byte would be stored at the higher address of RAM.
2961 However, contrast to this, Network Byte Order just take the totally
2962 opposite way to store the data, says, it will store the lower Byte at the
2963 lower address, and the higher Byte will stay at higher address.
2964
2965 For the current communication of network, we normally exchange the
2966 information by surveying the data package, every two host wants to
2967 communicate with each other must send and receive data package through
2968 network. In order to maintain the identity of data through the
2969 transmission in the network, the order of the Byte storage must changed
2970 before sending and after receiving the data.
2971
2972 There ten convenient functions to realize the conversion of Byte Order in
2973 GNUnet, as following:
2974
2975 @table @asis
2976
2977 @item uint16_t htons(uint16_t hostshort) Convert host byte order to net
2978 byte order with short int
2979 @item uint32_t htonl(uint32_t hostlong) Convert host byte
2980 order to net byte order with long int
2981 @item uint16_t ntohs(uint16_t netshort)
2982 Convert net byte order to host byte order with short int
2983 @item uint32_t
2984 ntohl(uint32_t netlong) Convert net byte order to host byte order with
2985 long int
2986 @item unsigned long long GNUNET_ntohll (unsigned long long netlonglong)
2987 Convert net byte order to host byte order with long long int
2988 @item unsigned long long GNUNET_htonll (unsigned long long hostlonglong)
2989 Convert host byte order to net byte order with long long int
2990 @item struct GNUNET_TIME_RelativeNBO GNUNET_TIME_relative_hton
2991 (struct GNUNET_TIME_Relative a) Convert relative time to network byte
2992 order.
2993 @item struct GNUNET_TIME_Relative GNUNET_TIME_relative_ntoh
2994 (struct GNUNET_TIME_RelativeNBO a) Convert relative time from network
2995 byte order.
2996 @item struct GNUNET_TIME_AbsoluteNBO GNUNET_TIME_absolute_hton
2997 (struct GNUNET_TIME_Absolute a) Convert relative time to network byte
2998 order.
2999 @item struct GNUNET_TIME_Absolute GNUNET_TIME_absolute_ntoh
3000 (struct GNUNET_TIME_AbsoluteNBO a) Convert relative time from network
3001 byte order.
3002 @end table
3003
3004 @cindex Cryptography API
3005 @node Cryptography API
3006 @subsection Cryptography API
3007
3008
3009 The gnunetutil APIs provides the cryptographic primitives used in GNUnet.
3010 GNUnet uses 2048 bit RSA keys for the session key exchange and for signing
3011 messages by peers and most other public-key operations. Most researchers
3012 in cryptography consider 2048 bit RSA keys as secure and practically
3013 unbreakable for a long time. The API provides functions to create a fresh
3014 key pair, read a private key from a file (or create a new file if the
3015 file does not exist), encrypt, decrypt, sign, verify and extraction of
3016 the public key into a format suitable for network transmission.
3017
3018 For the encryption of files and the actual data exchanged between peers
3019 GNUnet uses 256-bit AES encryption. Fresh, session keys are negotiated
3020 for every new connection.@ Again, there is no published technique to
3021 break this cipher in any realistic amount of time. The API provides
3022 functions for generation of keys, validation of keys (important for
3023 checking that decryptions using RSA succeeded), encryption and decryption.
3024
3025 GNUnet uses SHA-512 for computing one-way hash codes. The API provides
3026 functions to compute a hash over a block in memory or over a file on disk.
3027
3028 The crypto API also provides functions for randomizing a block of memory,
3029 obtaining a single random number and for generating a permutation of the
3030 numbers 0 to n-1. Random number generation distinguishes between WEAK and
3031 STRONG random number quality; WEAK random numbers are pseudo-random
3032 whereas STRONG random numbers use entropy gathered from the operating
3033 system.
3034
3035 Finally, the crypto API provides a means to deterministically generate a
3036 1024-bit RSA key from a hash code. These functions should most likely not
3037 be used by most applications; most importantly,
3038 GNUNET_CRYPTO_rsa_key_create_from_hash does not create an RSA-key that
3039 should be considered secure for traditional applications of RSA.
3040
3041 @cindex Message Queue API
3042 @node Message Queue API
3043 @subsection Message Queue API
3044
3045
3046 @strong{ Introduction }@
3047 Often, applications need to queue messages that
3048 are to be sent to other GNUnet peers, clients or services. As all of
3049 GNUnet's message-based communication APIs, by design, do not allow
3050 messages to be queued, it is common to implement custom message queues
3051 manually when they are needed. However, writing very similar code in
3052 multiple places is tedious and leads to code duplication.
3053
3054 MQ (for Message Queue) is an API that provides the functionality to
3055 implement and use message queues. We intend to eventually replace all of
3056 the custom message queue implementations in GNUnet with MQ.
3057
3058 @strong{ Basic Concepts }@
3059 The two most important entities in MQ are queues and envelopes.
3060
3061 Every queue is backed by a specific implementation (e.g. for mesh, stream,
3062 connection, server client, etc.) that will actually deliver the queued
3063 messages. For convenience,@ some queues also allow to specify a list of
3064 message handlers. The message queue will then also wait for incoming
3065 messages and dispatch them appropriately.
3066
3067 An envelope holds the the memory for a message, as well as metadata
3068 (Where is the envelope queued? What should happen after it has been
3069 sent?). Any envelope can only be queued in one message queue.
3070
3071 @strong{ Creating Queues }@
3072 The following is a list of currently available message queues. Note that
3073 to avoid layering issues, message queues for higher level APIs are not
3074 part of @code{libgnunetutil}, but@ the respective API itself provides the
3075 queue implementation.
3076
3077 @table @asis
3078
3079 @item @code{GNUNET_MQ_queue_for_connection_client}
3080 Transmits queued messages over a @code{GNUNET_CLIENT_Connection} handle.
3081 Also supports receiving with message handlers.
3082
3083 @item @code{GNUNET_MQ_queue_for_server_client}
3084 Transmits queued messages over a @code{GNUNET_SERVER_Client} handle. Does
3085 not support incoming message handlers.
3086
3087 @item @code{GNUNET_MESH_mq_create} Transmits queued messages over a
3088 @code{GNUNET_MESH_Tunnel} handle. Does not support incoming message
3089 handlers.
3090
3091 @item @code{GNUNET_MQ_queue_for_callbacks} This is the most general
3092 implementation. Instead of delivering and receiving messages with one of
3093 GNUnet's communication APIs, implementation callbacks are called. Refer to
3094 "Implementing Queues" for a more detailed explanation.
3095 @end table
3096
3097
3098 @strong{ Allocating Envelopes }@
3099 A GNUnet message (as defined by the GNUNET_MessageHeader) has three
3100 parts: The size, the type, and the body.
3101
3102 MQ provides macros to allocate an envelope containing a message
3103 conveniently, automatically setting the size and type fields of the
3104 message.
3105
3106 Consider the following simple message, with the body consisting of a
3107 single number value.
3108 @c why the empty code function?
3109 @code{}
3110
3111 @example
3112 struct NumberMessage @{
3113   /** Type: GNUNET_MESSAGE_TYPE_EXAMPLE_1 */
3114   struct GNUNET_MessageHeader header;
3115   uint32_t number GNUNET_PACKED;
3116 @};
3117 @end example
3118
3119 An envelope containing an instance of the NumberMessage can be
3120 constructed like this:
3121
3122 @example
3123 struct GNUNET_MQ_Envelope *ev;
3124 struct NumberMessage *msg;
3125 ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_EXAMPLE_1);
3126 msg->number = htonl (42);
3127 @end example
3128
3129 In the above code, @code{GNUNET_MQ_msg} is a macro. The return value is
3130 the newly allocated envelope. The first argument must be a pointer to some
3131 @code{struct} containing a @code{struct GNUNET_MessageHeader header}
3132 field, while the second argument is the desired message type, in host
3133 byte order.
3134
3135 The @code{msg} pointer now points to an allocated message, where the
3136 message type and the message size are already set. The message's size is
3137 inferred from the type of the @code{msg} pointer: It will be set to
3138 'sizeof(*msg)', properly converted to network byte order.
3139
3140 If the message body's size is dynamic, the the macro
3141 @code{GNUNET_MQ_msg_extra} can be used to allocate an envelope whose
3142 message has additional space allocated after the @code{msg} structure.
3143
3144 If no structure has been defined for the message,
3145 @code{GNUNET_MQ_msg_header_extra} can be used to allocate additional space
3146 after the message header. The first argument then must be a pointer to a
3147 @code{GNUNET_MessageHeader}.
3148
3149 @strong{Envelope Properties}@
3150 A few functions in MQ allow to set additional properties on envelopes:
3151
3152 @table @asis
3153
3154 @item @code{GNUNET_MQ_notify_sent} Allows to specify a function that will
3155 be called once the envelope's message has been sent irrevocably.
3156 An envelope can be canceled precisely up to the@ point where the notify
3157 sent callback has been called.
3158
3159 @item @code{GNUNET_MQ_disable_corking} No corking will be used when
3160 sending the message. Not every@ queue supports this flag, per default,
3161 envelopes are sent with corking.@
3162
3163 @end table
3164
3165
3166 @strong{Sending Envelopes}@
3167 Once an envelope has been constructed, it can be queued for sending with
3168 @code{GNUNET_MQ_send}.
3169
3170 Note that in order to avoid memory leaks, an envelope must either be sent
3171 (the queue will free it) or destroyed explicitly with
3172 @code{GNUNET_MQ_discard}.
3173
3174 @strong{Canceling Envelopes}@
3175 An envelope queued with @code{GNUNET_MQ_send} can be canceled with
3176 @code{GNUNET_MQ_cancel}. Note that after the notify sent callback has
3177 been called, canceling a message results in undefined behavior.
3178 Thus it is unsafe to cancel an envelope that does not have a notify sent
3179 callback. When canceling an envelope, it is not necessary@ to call
3180 @code{GNUNET_MQ_discard}, and the envelope can't be sent again.
3181
3182 @strong{ Implementing Queues }@
3183 @code{TODO}
3184
3185 @cindex Service API
3186 @node Service API
3187 @subsection Service API
3188
3189
3190 Most GNUnet code lives in the form of services. Services are processes
3191 that offer an API for other components of the system to build on. Those
3192 other components can be command-line tools for users, graphical user
3193 interfaces or other services. Services provide their API using an IPC
3194 protocol. For this, each service must listen on either a TCP port or a
3195 UNIX domain socket; for this, the service implementation uses the server
3196 API. This use of server is exposed directly to the users of the service
3197 API. Thus, when using the service API, one is usually also often using
3198 large parts of the server API. The service API provides various
3199 convenience functions, such as parsing command-line arguments and the
3200 configuration file, which are not found in the server API.
3201 The dual to the service/server API is the client API, which can be used to
3202 access services.
3203
3204 The most common way to start a service is to use the
3205 @code{GNUNET_SERVICE_run} function from the program's main function.
3206 @code{GNUNET_SERVICE_run} will then parse the command line and
3207 configuration files and, based on the options found there,
3208 start the server. It will then give back control to the main
3209 program, passing the server and the configuration to the
3210 @code{GNUNET_SERVICE_Main} callback. @code{GNUNET_SERVICE_run}
3211 will also take care of starting the scheduler loop.
3212 If this is inappropriate (for example, because the scheduler loop
3213 is already running), @code{GNUNET_SERVICE_start} and
3214 related functions provide an alternative to @code{GNUNET_SERVICE_run}.
3215
3216 When starting a service, the service_name option is used to determine
3217 which sections in the configuration file should be used to configure the
3218 service. A typical value here is the name of the @file{src/}
3219 sub-directory, for example @file{statistics}.
3220 The same string would also be given to
3221 @code{GNUNET_CLIENT_connect} to access the service.
3222
3223 Once a service has been initialized, the program should use the
3224 @code{GNUNET_SERVICE_Main} callback to register message handlers
3225 using @code{GNUNET_SERVER_add_handlers}.
3226 The service will already have registered a handler for the
3227 "TEST" message.
3228
3229 @findex GNUNET_SERVICE_Options
3230 The option bitfield (@code{enum GNUNET_SERVICE_Options})
3231 determines how a service should behave during shutdown.
3232 There are three key strategies:
3233
3234 @table @asis
3235
3236 @item instant (@code{GNUNET_SERVICE_OPTION_NONE})
3237 Upon receiving the shutdown
3238 signal from the scheduler, the service immediately terminates the server,
3239 closing all existing connections with clients.
3240 @item manual (@code{GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN})
3241 The service does nothing by itself
3242 during shutdown. The main program will need to take the appropriate
3243 action by calling GNUNET_SERVER_destroy or GNUNET_SERVICE_stop (depending
3244 on how the service was initialized) to terminate the service. This method
3245 is used by gnunet-service-arm and rather uncommon.
3246 @item soft (@code{GNUNET_SERVICE_OPTION_SOFT_SHUTDOWN})
3247 Upon receiving the shutdown signal from the scheduler,
3248 the service immediately tells the server to stop
3249 listening for incoming clients. Requests from normal existing clients are
3250 still processed and the server/service terminates once all normal clients
3251 have disconnected. Clients that are not expected to ever disconnect (such
3252 as clients that monitor performance values) can be marked as 'monitor'
3253 clients using GNUNET_SERVER_client_mark_monitor. Those clients will
3254 continue to be processed until all 'normal' clients have disconnected.
3255 Then, the server will terminate, closing the monitor connections.
3256 This mode is for example used by 'statistics', allowing existing 'normal'
3257 clients to set (possibly persistent) statistic values before terminating.
3258
3259 @end table
3260
3261 @c ***********************************************************************
3262 @node Optimizing Memory Consumption of GNUnet's (Multi-) Hash Maps
3263 @subsection Optimizing Memory Consumption of GNUnet's (Multi-) Hash Maps
3264
3265
3266 A commonly used data structure in GNUnet is a (multi-)hash map. It is most
3267 often used to map a peer identity to some data structure, but also to map
3268 arbitrary keys to values (for example to track requests in the distributed
3269 hash table or in file-sharing). As it is commonly used, the DHT is
3270 actually sometimes responsible for a large share of GNUnet's overall
3271 memory consumption (for some processes, 30% is not uncommon). The
3272 following text documents some API quirks (and their implications for
3273 applications) that were recently introduced to minimize the footprint of
3274 the hash map.
3275
3276
3277 @c ***********************************************************************
3278 @menu
3279 * Analysis::
3280 * Solution::
3281 * Migration::
3282 * Conclusion::
3283 * Availability::
3284 @end menu
3285
3286 @node Analysis
3287 @subsubsection Analysis
3288
3289
3290 The main reason for the "excessive" memory consumption by the hash map is
3291 that GNUnet uses 512-bit cryptographic hash codes --- and the
3292 (multi-)hash map also uses the same 512-bit 'struct GNUNET_HashCode'. As
3293 a result, storing just the keys requires 64 bytes of memory for each key.
3294 As some applications like to keep a large number of entries in the hash
3295 map (after all, that's what maps are good for), 64 bytes per hash is
3296 significant: keeping a pointer to the value and having a linked list for
3297 collisions consume between 8 and 16 bytes, and 'malloc' may add about the
3298 same overhead per allocation, putting us in the 16 to 32 byte per entry
3299 ballpark. Adding a 64-byte key then triples the overall memory
3300 requirement for the hash map.
3301
3302 To make things "worse", most of the time storing the key in the hash map
3303 is not required: it is typically already in memory elsewhere! In most
3304 cases, the values stored in the hash map are some application-specific
3305 struct that _also_ contains the hash. Here is a simplified example:
3306
3307 @example
3308 struct MyValue @{
3309 struct GNUNET_HashCode key;
3310 unsigned int my_data; @};
3311
3312 // ...
3313 val = GNUNET_malloc (sizeof (struct MyValue));
3314 val->key = key;
3315 val->my_data = 42;
3316 GNUNET_CONTAINER_multihashmap_put (map, &key, val, ...);
3317 @end example
3318
3319 This is a common pattern as later the entries might need to be removed,
3320 and at that time it is convenient to have the key immediately at hand:
3321
3322 @example
3323 GNUNET_CONTAINER_multihashmap_remove (map, &val->key, val);
3324 @end example
3325
3326
3327 Note that here we end up with two times 64 bytes for the key, plus maybe
3328 64 bytes total for the rest of the 'struct MyValue' and the map entry in
3329 the hash map. The resulting redundant storage of the key increases
3330 overall memory consumption per entry from the "optimal" 128 bytes to 192
3331 bytes. This is not just an extreme example: overheads in practice are
3332 actually sometimes close to those highlighted in this example. This is
3333 especially true for maps with a significant number of entries, as there
3334 we tend to really try to keep the entries small.
3335
3336 @c ***********************************************************************
3337 @node Solution
3338 @subsubsection Solution
3339
3340
3341 The solution that has now been implemented is to @strong{optionally}
3342 allow the hash map to not make a (deep) copy of the hash but instead have
3343 a pointer to the hash/key in the entry. This reduces the memory
3344 consumption for the key from 64 bytes to 4 to 8 bytes. However, it can
3345 also only work if the key is actually stored in the entry (which is the
3346 case most of the time) and if the entry does not modify the key (which in
3347 all of the code I'm aware of has been always the case if there key is
3348 stored in the entry). Finally, when the client stores an entry in the
3349 hash map, it @strong{must} provide a pointer to the key within the entry,
3350 not just a pointer to a transient location of the key. If
3351 the client code does not meet these requirements, the result is a dangling
3352 pointer and undefined behavior of the (multi-)hash map API.
3353
3354 @c ***********************************************************************
3355 @node Migration
3356 @subsubsection Migration
3357
3358
3359 To use the new feature, first check that the values contain the respective
3360 key (and never modify it). Then, all calls to
3361 @code{GNUNET_CONTAINER_multihashmap_put} on the respective map must be
3362 audited and most likely changed to pass a pointer into the value's struct.
3363 For the initial example, the new code would look like this:
3364
3365 @example
3366 struct MyValue @{
3367 struct GNUNET_HashCode key;
3368 unsigned int my_data; @};
3369
3370 // ...
3371 val = GNUNET_malloc (sizeof (struct MyValue));
3372 val->key = key; val->my_data = 42;
3373 GNUNET_CONTAINER_multihashmap_put (map, &val->key, val, ...);
3374 @end example
3375
3376
3377 Note that @code{&val} was changed to @code{&val->key} in the argument to
3378 the @code{put} call. This is critical as often @code{key} is on the stack
3379 or in some other transient data structure and thus having the hash map
3380 keep a pointer to @code{key} would not work. Only the key inside of
3381 @code{val} has the same lifetime as the entry in the map (this must of
3382 course be checked as well). Naturally, @code{val->key} must be
3383 initialized before the @code{put} call. Once all @code{put} calls have
3384 been converted and double-checked, you can change the call to create the
3385 hash map from
3386
3387 @example
3388 map =
3389 GNUNET_CONTAINER_multihashmap_create (SIZE, GNUNET_NO);
3390 @end example
3391
3392 to
3393
3394 @example
3395 map = GNUNET_CONTAINER_multihashmap_create (SIZE, GNUNET_YES);
3396 @end example
3397
3398 If everything was done correctly, you now use about 60 bytes less memory
3399 per entry in @code{map}. However, if now (or in the future) any call to
3400 @code{put} does not ensure that the given key is valid until the entry is
3401 removed from the map, undefined behavior is likely to be observed.
3402
3403 @c ***********************************************************************
3404 @node Conclusion
3405 @subsubsection Conclusion
3406
3407
3408 The new optimization can is often applicable and can result in a
3409 reduction in memory consumption of up to 30% in practice. However, it
3410 makes the code less robust as additional invariants are imposed on the
3411 multi hash map client. Thus applications should refrain from enabling the
3412 new mode unless the resulting performance increase is deemed significant
3413 enough. In particular, it should generally not be used in new code (wait
3414 at least until benchmarks exist).
3415
3416 @c ***********************************************************************
3417 @node Availability
3418 @subsubsection Availability
3419
3420
3421 The new multi hash map code was committed in SVN 24319 (which made its
3422 way into GNUnet version 0.9.4).
3423 Various subsystems (transport, core, dht, file-sharing) were
3424 previously audited and modified to take advantage of the new capability.
3425 In particular, memory consumption of the file-sharing service is expected
3426 to drop by 20-30% due to this change.
3427
3428
3429 @cindex CONTAINER_MDLL API
3430 @node CONTAINER_MDLL API
3431 @subsection CONTAINER_MDLL API
3432
3433
3434 This text documents the GNUNET_CONTAINER_MDLL API. The
3435 GNUNET_CONTAINER_MDLL API is similar to the GNUNET_CONTAINER_DLL API in
3436 that it provides operations for the construction and manipulation of
3437 doubly-linked lists. The key difference to the (simpler) DLL-API is that
3438 the MDLL-version allows a single element (instance of a "struct") to be
3439 in multiple linked lists at the same time.
3440
3441 Like the DLL API, the MDLL API stores (most of) the data structures for
3442 the doubly-linked list with the respective elements; only the 'head' and
3443 'tail' pointers are stored "elsewhere" --- and the application needs to
3444 provide the locations of head and tail to each of the calls in the
3445 MDLL API. The key difference for the MDLL API is that the "next" and
3446 "previous" pointers in the struct can no longer be simply called "next"
3447 and "prev" --- after all, the element may be in multiple doubly-linked
3448 lists, so we cannot just have one "next" and one "prev" pointer!
3449
3450 The solution is to have multiple fields that must have a name of the
3451 format "next_XX" and "prev_XX" where "XX" is the name of one of the
3452 doubly-linked lists. Here is a simple example:
3453
3454 @example
3455 struct MyMultiListElement @{
3456   struct MyMultiListElement *next_ALIST;
3457   struct MyMultiListElement *prev_ALIST;
3458   struct MyMultiListElement *next_BLIST;
3459   struct MyMultiListElement *prev_BLIST;
3460   void
3461   *data;
3462 @};
3463 @end example
3464
3465
3466 Note that by convention, we use all-uppercase letters for the list names.
3467 In addition, the program needs to have a location for the head and tail
3468 pointers for both lists, for example:
3469
3470 @example
3471 static struct MyMultiListElement *head_ALIST;
3472 static struct MyMultiListElement *tail_ALIST;
3473 static struct MyMultiListElement *head_BLIST;
3474 static struct MyMultiListElement *tail_BLIST;
3475 @end example
3476
3477
3478 Using the MDLL-macros, we can now insert an element into the ALIST:
3479
3480 @example
3481 GNUNET_CONTAINER_MDLL_insert (ALIST, head_ALIST, tail_ALIST, element);
3482 @end example
3483
3484
3485 Passing "ALIST" as the first argument to MDLL specifies which of the
3486 next/prev fields in the 'struct MyMultiListElement' should be used. The
3487 extra "ALIST" argument and the "_ALIST" in the names of the
3488 next/prev-members are the only differences between the MDDL and DLL-API.
3489 Like the DLL-API, the MDLL-API offers functions for inserting (at head,
3490 at tail, after a given element) and removing elements from the list.
3491 Iterating over the list should be done by directly accessing the
3492 "next_XX" and/or "prev_XX" members.
3493
3494 @cindex Automatic Restart Manager
3495 @cindex ARM
3496 @node Automatic Restart Manager (ARM)
3497 @section Automatic Restart Manager (ARM)
3498
3499
3500 GNUnet's Automated Restart Manager (ARM) is the GNUnet service responsible
3501 for system initialization and service babysitting. ARM starts and halts
3502 services, detects configuration changes and restarts services impacted by
3503 the changes as needed. It's also responsible for restarting services in
3504 case of crashes and is planned to incorporate automatic debugging for
3505 diagnosing service crashes providing developers insights about crash
3506 reasons. The purpose of this document is to give GNUnet developer an idea
3507 about how ARM works and how to interact with it.
3508
3509 @menu
3510 * Basic functionality::
3511 * Key configuration options::
3512 * ARM - Availability::
3513 * Reliability::
3514 @end menu
3515
3516 @c ***********************************************************************
3517 @node Basic functionality
3518 @subsection Basic functionality
3519
3520
3521 @itemize @bullet
3522 @item ARM source code can be found under "src/arm".@ Service processes are
3523 managed by the functions in "gnunet-service-arm.c" which is controlled
3524 with "gnunet-arm.c" (main function in that file is ARM's entry point).
3525
3526 @item The functions responsible for communicating with ARM , starting and
3527 stopping services -including ARM service itself- are provided by the
3528 ARM API "arm_api.c".@ Function: GNUNET_ARM_connect() returns to the caller
3529 an ARM handle after setting it to the caller's context (configuration and
3530 scheduler in use). This handle can be used afterwards by the caller to
3531 communicate with ARM. Functions GNUNET_ARM_start_service() and
3532 GNUNET_ARM_stop_service() are used for starting and stopping services
3533 respectively.
3534
3535 @item A typical example of using these basic ARM services can be found in
3536 file test_arm_api.c. The test case connects to ARM, starts it, then uses
3537 it to start a service "resolver", stops the "resolver" then stops "ARM".
3538 @end itemize
3539
3540 @c ***********************************************************************
3541 @node Key configuration options
3542 @subsection Key configuration options
3543
3544
3545 Configurations for ARM and services should be available in a .conf file
3546 (As an example, see test_arm_api_data.conf). When running ARM, the
3547 configuration file to use should be passed to the command:
3548
3549 @example
3550 $ gnunet-arm -s -c configuration_to_use.conf
3551 @end example
3552
3553 If no configuration is passed, the default configuration file will be used
3554 (see GNUNET_PREFIX/share/gnunet/defaults.conf which is created from
3555 contrib/defaults.conf).@ Each of the services is having a section starting
3556 by the service name between square brackets, for example: "[arm]".
3557 The following options configure how ARM configures or interacts with the
3558 various services:
3559
3560 @table @asis
3561
3562 @item PORT Port number on which the service is listening for incoming TCP
3563 connections. ARM will start the services should it notice a request at
3564 this port.
3565
3566 @item HOSTNAME Specifies on which host the service is deployed. Note
3567 that ARM can only start services that are running on the local system
3568 (but will not check that the hostname matches the local machine name).
3569 This option is used by the @code{gnunet_client_lib.h} implementation to
3570 determine which system to connect to. The default is "localhost".
3571
3572 @item BINARY The name of the service binary file.
3573
3574 @item OPTIONS To be passed to the service.
3575
3576 @item PREFIX A command to pre-pend to the actual command, for example,
3577 running a service with "valgrind" or "gdb"
3578
3579 @item DEBUG Run in debug mode (much verbosity).
3580
3581 @item START_ON_DEMAND ARM will listen to UNIX domain socket and/or TCP port of
3582 the service and start the service on-demand.
3583
3584 @item IMMEDIATE_START ARM will always start this service when the peer
3585 is started.
3586
3587 @item ACCEPT_FROM IPv4 addresses the service accepts connections from.
3588
3589 @item ACCEPT_FROM6 IPv6 addresses the service accepts connections from.
3590
3591 @end table
3592
3593
3594 Options that impact the operation of ARM overall are in the "[arm]"
3595 section. ARM is a normal service and has (except for START_ON_DEMAND) all of the
3596 options that other services do. In addition, ARM has the
3597 following options:
3598
3599 @table @asis
3600
3601 @item GLOBAL_PREFIX Command to be pre-pended to all services that are
3602 going to run.
3603
3604 @item GLOBAL_POSTFIX Global option that will be supplied to all the
3605 services that are going to run.
3606
3607 @end table
3608
3609 @c ***********************************************************************
3610 @node ARM - Availability
3611 @subsection ARM - Availability
3612
3613
3614 As mentioned before, one of the features provided by ARM is starting
3615 services on demand. Consider the example of one service "client" that
3616 wants to connect to another service a "server". The "client" will ask ARM
3617 to run the "server". ARM starts the "server". The "server" starts
3618 listening to incoming connections. The "client" will establish a
3619 connection with the "server". And then, they will start to communicate
3620 together.@ One problem with that scheme is that it's slow!@
3621 The "client" service wants to communicate with the "server" service at
3622 once and is not willing wait for it to be started and listening to
3623 incoming connections before serving its request.@ One solution for that
3624 problem will be that ARM starts all services as default services. That
3625 solution will solve the problem, yet, it's not quite practical, for some
3626 services that are going to be started can never be used or are going to
3627 be used after a relatively long time.@
3628 The approach followed by ARM to solve this problem is as follows:
3629
3630 @itemize @bullet
3631
3632 @item For each service having a PORT field in the configuration file and
3633 that is not one of the default services ( a service that accepts incoming
3634 connections from clients), ARM creates listening sockets for all addresses
3635 associated with that service.
3636
3637 @item The "client" will immediately establish a connection with
3638 the "server".
3639
3640 @item ARM --- pretending to be the "server" --- will listen on the
3641 respective port and notice the incoming connection from the "client"
3642 (but not accept it), instead
3643
3644 @item Once there is an incoming connection, ARM will start the "server",
3645 passing on the listen sockets (now, the service is started and can do its
3646 work).
3647
3648 @item Other client services now can directly connect directly to the
3649 "server".
3650
3651 @end itemize
3652
3653 @c ***********************************************************************
3654 @node Reliability
3655 @subsection Reliability
3656
3657 One of the features provided by ARM, is the automatic restart of crashed
3658 services.@ ARM needs to know which of the running services died. Function
3659 "gnunet-service-arm.c/maint_child_death()" is responsible for that. The
3660 function is scheduled to run upon receiving a SIGCHLD signal. The
3661 function, then, iterates ARM's list of services running and monitors
3662 which service has died (crashed). For all crashing services, ARM restarts
3663 them.@
3664 Now, considering the case of a service having a serious problem causing it
3665 to crash each time it's started by ARM. If ARM keeps blindly restarting
3666 such a service, we are going to have the pattern:
3667 start-crash-restart-crash-restart-crash and so forth!! Which is of course
3668 not practical.@
3669 For that reason, ARM schedules the service to be restarted after waiting
3670 for some delay that grows exponentially with each crash/restart of that
3671 service.@ To clarify the idea, considering the following example:
3672
3673 @itemize @bullet
3674
3675 @item Service S crashed.
3676
3677 @item ARM receives the SIGCHLD and inspects its list of services to find
3678 the dead one(s).
3679
3680 @item ARM finds S dead and schedules it for restarting after "backoff"
3681 time which is initially set to 1ms. ARM will double the backoff time
3682 correspondent to S (now backoff(S) = 2ms)
3683
3684 @item Because there is a severe problem with S, it crashed again.
3685
3686 @item Again ARM receives the SIGCHLD and detects that it's S again that's
3687 crashed. ARM schedules it for restarting but after its new backoff time
3688 (which became 2ms), and doubles its backoff time (now backoff(S) = 4).
3689
3690 @item and so on, until backoff(S) reaches a certain threshold
3691 (@code{EXPONENTIAL_BACKOFF_THRESHOLD} is set to half an hour),
3692 after reaching it, backoff(S) will remain half an hour,
3693 hence ARM won't be busy for a lot of time trying to restart a
3694 problematic service.
3695 @end itemize
3696
3697 @cindex TRANSPORT Subsystem
3698 @node TRANSPORT Subsystem
3699 @section TRANSPORT Subsystem
3700
3701
3702 This chapter documents how the GNUnet transport subsystem works. The
3703 GNUnet transport subsystem consists of three main components: the
3704 transport API (the interface used by the rest of the system to access the
3705 transport service), the transport service itself (most of the interesting
3706 functions, such as choosing transports, happens here) and the transport
3707 plugins. A transport plugin is a concrete implementation for how two
3708 GNUnet peers communicate; many plugins exist, for example for
3709 communication via TCP, UDP, HTTP, HTTPS and others. Finally, the
3710 transport subsystem uses supporting code, especially the NAT/UPnP
3711 library to help with tasks such as NAT traversal.
3712
3713 Key tasks of the transport service include:
3714
3715 @itemize @bullet
3716
3717 @item Create our HELLO message, notify clients and neighbours if our HELLO
3718 changes (using NAT library as necessary)
3719
3720 @item Validate HELLOs from other peers (send PING), allow other peers to
3721 validate our HELLO's addresses (send PONG)
3722
3723 @item Upon request, establish connections to other peers (using address
3724 selection from ATS subsystem) and maintain them (again using PINGs and
3725 PONGs) as long as desired
3726
3727 @item Accept incoming connections, give ATS service the opportunity to
3728 switch communication channels
3729
3730 @item Notify clients about peers that have connected to us or that have
3731 been disconnected from us
3732
3733 @item If a (stateful) connection goes down unexpectedly (without explicit
3734 DISCONNECT), quickly attempt to recover (without notifying clients) but do
3735 notify clients quickly if reconnecting fails
3736
3737 @item Send (payload) messages arriving from clients to other peers via
3738 transport plugins and receive messages from other peers, forwarding
3739 those to clients
3740
3741 @item Enforce inbound traffic limits (using flow-control if it is
3742 applicable); outbound traffic limits are enforced by CORE, not by us (!)
3743
3744 @item Enforce restrictions on P2P connection as specified by the blacklist
3745 configuration and blacklisting clients
3746 @end itemize
3747
3748 Note that the term "clients" in the list above really refers to the
3749 GNUnet-CORE service, as CORE is typically the only client of the
3750 transport service.
3751
3752 @menu
3753 * Address validation protocol::
3754 @end menu
3755
3756 @node Address validation protocol
3757 @subsection Address validation protocol
3758
3759
3760 This section documents how the GNUnet transport service validates
3761 connections with other peers. It is a high-level description of the
3762 protocol necessary to understand the details of the implementation. It
3763 should be noted that when we talk about PING and PONG messages in this
3764 section, we refer to transport-level PING and PONG messages, which are
3765 different from core-level PING and PONG messages (both in implementation
3766 and function).
3767
3768 The goal of transport-level address validation is to minimize the chances
3769 of a successful man-in-the-middle attack against GNUnet peers on the
3770 transport level. Such an attack would not allow the adversary to decrypt
3771 the P2P transmissions, but a successful attacker could at least measure
3772 traffic volumes and latencies (raising the adversaries capabilities by
3773 those of a global passive adversary in the worst case). The scenarios we
3774 are concerned about is an attacker, Mallory, giving a @code{HELLO} to
3775 Alice that claims to be for Bob, but contains Mallory's IP address
3776 instead of Bobs (for some transport).
3777 Mallory would then forward the traffic to Bob (by initiating a
3778 connection to Bob and claiming to be Alice). As a further
3779 complication, the scheme has to work even if say Alice is behind a NAT
3780 without traversal support and hence has no address of her own (and thus
3781 Alice must always initiate the connection to Bob).
3782
3783 An additional constraint is that @code{HELLO} messages do not contain a
3784 cryptographic signature since other peers must be able to edit
3785 (i.e. remove) addresses from the @code{HELLO} at any time (this was
3786 not true in GNUnet 0.8.x). A basic @strong{assumption} is that each peer
3787 knows the set of possible network addresses that it @strong{might}
3788 be reachable under (so for example, the external IP address of the
3789 NAT plus the LAN address(es) with the respective ports).
3790
3791 The solution is the following. If Alice wants to validate that a given
3792 address for Bob is valid (i.e. is actually established @strong{directly}
3793 with the intended target), she sends a PING message over that connection
3794 to Bob. Note that in this case, Alice initiated the connection so only
3795 Alice knows which address was used for sure (Alice may be behind NAT, so
3796 whatever address Bob sees may not be an address Alice knows she has).
3797 Bob checks that the address given in the @code{PING} is actually one
3798 of Bob's addresses (ie: does not belong to Mallory), and if it is,
3799 sends back a @code{PONG} (with a signature that says that Bob
3800 owns/uses the address from the @code{PING}).
3801 Alice checks the signature and is happy if it is valid and the address
3802 in the @code{PONG} is the address Alice used.
3803 This is similar to the 0.8.x protocol where the @code{HELLO} contained a
3804 signature from Bob for each address used by Bob.
3805 Here, the purpose code for the signature is
3806 @code{GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN}. After this, Alice will
3807 remember Bob's address and consider the address valid for a while (12h in
3808 the current implementation). Note that after this exchange, Alice only
3809 considers Bob's address to be valid, the connection itself is not
3810 considered 'established'. In particular, Alice may have many addresses
3811 for Bob that Alice considers valid.
3812
3813 The @code{PONG} message is protected with a nonce/challenge against replay
3814 attacks (@uref{http://en.wikipedia.org/wiki/Replay_attack, replay})
3815 and uses an expiration time for the signature (but those are almost
3816 implementation details).
3817
3818 @cindex NAT library
3819 @node NAT library
3820 @section NAT library
3821
3822
3823 The goal of the GNUnet NAT library is to provide a general-purpose API for
3824 NAT traversal @strong{without} third-party support. So protocols that
3825 involve contacting a third peer to help establish a connection between
3826 two peers are outside of the scope of this API. That does not mean that
3827 GNUnet doesn't support involving a third peer (we can do this with the
3828 distance-vector transport or using application-level protocols), it just
3829 means that the NAT API is not concerned with this possibility. The API is
3830 written so that it will work for IPv6-NAT in the future as well as
3831 current IPv4-NAT. Furthermore, the NAT API is always used, even for peers
3832 that are not behind NAT --- in that case, the mapping provided is simply
3833 the identity.
3834
3835 NAT traversal is initiated by calling @code{GNUNET_NAT_register}. Given a
3836 set of addresses that the peer has locally bound to (TCP or UDP), the NAT
3837 library will return (via callback) a (possibly longer) list of addresses
3838 the peer @strong{might} be reachable under. Internally, depending on the
3839 configuration, the NAT library will try to punch a hole (using UPnP) or
3840 just "know" that the NAT was manually punched and generate the respective
3841 external IP address (the one that should be globally visible) based on
3842 the given information.
3843
3844 The NAT library also supports ICMP-based NAT traversal. Here, the other
3845 peer can request connection-reversal by this peer (in this special case,
3846 the peer is even allowed to configure a port number of zero). If the NAT
3847 library detects a connection-reversal request, it returns the respective
3848 target address to the client as well. It should be noted that
3849 connection-reversal is currently only intended for TCP, so other plugins
3850 @strong{must} pass @code{NULL} for the reversal callback. Naturally, the
3851 NAT library also supports requesting connection reversal from a remote
3852 peer (@code{GNUNET_NAT_run_client}).
3853
3854 Once initialized, the NAT handle can be used to test if a given address is
3855 possibly a valid address for this peer (@code{GNUNET_NAT_test_address}).
3856 This is used for validating our addresses when generating PONGs.
3857
3858 Finally, the NAT library contains an API to test if our NAT configuration
3859 is correct. Using @code{GNUNET_NAT_test_start} @strong{before} binding to
3860 the respective port, the NAT library can be used to test if the
3861 configuration works. The test function act as a local client, initialize
3862 the NAT traversal and then contact a @code{gnunet-nat-server} (running by
3863 default on @code{gnunet.org}) and ask for a connection to be established.
3864 This way, it is easy to test if the current NAT configuration is valid.
3865
3866 @node Distance-Vector plugin
3867 @section Distance-Vector plugin
3868
3869
3870 The Distance Vector (DV) transport is a transport mechanism that allows
3871 peers to act as relays for each other, thereby connecting peers that would
3872 otherwise be unable to connect. This gives a larger connection set to
3873 applications that may work better with more peers to choose from (for
3874 example, File Sharing and/or DHT).
3875
3876 The Distance Vector transport essentially has two functions. The first is
3877 "gossiping" connection information about more distant peers to directly
3878 connected peers. The second is taking messages intended for non-directly
3879 connected peers and encapsulating them in a DV wrapper that contains the
3880 required information for routing the message through forwarding peers. Via
3881 gossiping, optimal routes through the known DV neighborhood are discovered
3882 and utilized and the message encapsulation provides some benefits in
3883 addition to simply getting the message from the correct source to the
3884 proper destination.
3885
3886 The gossiping function of DV provides an up to date routing table of
3887 peers that are available up to some number of hops. We call this a
3888 fisheye view of the network (like a fish, nearby objects are known while
3889 more distant ones unknown). Gossip messages are sent only to directly
3890 connected peers, but they are sent about other knowns peers within the
3891 "fisheye distance". Whenever two peers connect, they immediately gossip
3892 to each other about their appropriate other neighbors. They also gossip
3893 about the newly connected peer to previously
3894 connected neighbors. In order to keep the routing tables up to date,
3895 disconnect notifications are propagated as gossip as well (because
3896 disconnects may not be sent/received, timeouts are also used remove
3897 stagnant routing table entries).
3898
3899 Routing of messages via DV is straightforward. When the DV transport is
3900 notified of a message destined for a non-direct neighbor, the appropriate
3901 forwarding peer is selected, and the base message is encapsulated in a DV
3902 message which contains information about the initial peer and the intended
3903 recipient. At each forwarding hop, the initial peer is validated (the
3904 forwarding peer ensures that it has the initial peer in its neighborhood,
3905 otherwise the message is dropped). Next the base message is
3906 re-encapsulated in a new DV message for the next hop in the forwarding
3907 chain (or delivered to the current peer, if it has arrived at the
3908 destination).
3909
3910 Assume a three peer network with peers Alice, Bob and Carol. Assume that
3911
3912 @example
3913 Alice <-> Bob and Bob <-> Carol
3914 @end example
3915
3916 @noindent
3917 are direct (e.g. over TCP or UDP transports) connections, but that
3918 Alice cannot directly connect to Carol.
3919 This may be the case due to NAT or firewall restrictions, or perhaps
3920 based on one of the peers respective configurations. If the Distance
3921 Vector transport is enabled on all three peers, it will automatically
3922 discover (from the gossip protocol) that Alice and Carol can connect via
3923 Bob and provide a "virtual" Alice <-> Carol connection. Routing between
3924 Alice and Carol happens as follows; Alice creates a message destined for
3925 Carol and notifies the DV transport about it. The DV transport at Alice
3926 looks up Carol in the routing table and finds that the message must be
3927 sent through Bob for Carol. The message is encapsulated setting Alice as
3928 the initiator and Carol as the destination and sent to Bob. Bob receives
3929 the messages, verifies that both Alice and Carol are known to Bob, and
3930 re-wraps the message in a new DV message for Carol.
3931 The DV transport at Carol receives this message, unwraps the original
3932 message, and delivers it to Carol as though it came directly from Alice.
3933
3934 @cindex SMTP plugin
3935 @node SMTP plugin
3936 @section SMTP plugin
3937
3938 @c TODO: Update!
3939
3940 This section describes the new SMTP transport plugin for GNUnet as it
3941 exists in the 0.7.x and 0.8.x branch. SMTP support is currently not
3942 available in GNUnet 0.9.x. This page also describes the transport layer
3943 abstraction (as it existed in 0.7.x and 0.8.x) in more detail and gives
3944 some benchmarking results. The performance results presented are quite
3945 old and maybe outdated at this point.
3946 For the readers in the year 2019, you will notice by the mention of
3947 version 0.7, 0.8, and 0.9 that this section has to be taken with your
3948 usual grain of salt and be updated eventually.
3949
3950 @itemize @bullet
3951 @item Why use SMTP for a peer-to-peer transport?
3952 @item SMTPHow does it work?
3953 @item How do I configure my peer?
3954 @item How do I test if it works?
3955 @item How fast is it?
3956 @item Is there any additional documentation?
3957 @end itemize
3958
3959
3960 @menu
3961 * Why use SMTP for a peer-to-peer transport?::
3962 * How does it work?::
3963 * How do I configure my peer?::
3964 * How do I test if it works?::
3965 * How fast is it?::
3966 @end menu
3967
3968 @node Why use SMTP for a peer-to-peer transport?
3969 @subsection Why use SMTP for a peer-to-peer transport?
3970
3971
3972 There are many reasons why one would not want to use SMTP:
3973
3974 @itemize @bullet
3975 @item SMTP is using more bandwidth than TCP, UDP or HTTP
3976 @item SMTP has a much higher latency.
3977 @item SMTP requires significantly more computation (encoding and decoding
3978 time) for the peers.
3979 @item SMTP is significantly more complicated to configure.
3980 @item SMTP may be abused by tricking GNUnet into sending mail to@
3981 non-participating third parties.
3982 @end itemize
3983
3984 So why would anybody want to use SMTP?
3985 @itemize @bullet
3986 @item SMTP can be used to contact peers behind NAT boxes (in virtual
3987 private networks).
3988 @item SMTP can be used to circumvent policies that limit or prohibit
3989 peer-to-peer traffic by masking as "legitimate" traffic.
3990 @item SMTP uses E-mail addresses which are independent of a specific IP,
3991 which can be useful to address peers that use dynamic IP addresses.
3992 @item SMTP can be used to initiate a connection (e.g. initial address
3993 exchange) and peers can then negotiate the use of a more efficient
3994 protocol (e.g. TCP) for the actual communication.
3995 @end itemize
3996
3997 In summary, SMTP can for example be used to send a message to a peer
3998 behind a NAT box that has a dynamic IP to tell the peer to establish a
3999 TCP connection to a peer outside of the private network. Even an
4000 extraordinary overhead for this first message would be irrelevant in this
4001 type of situation.
4002
4003 @node How does it work?
4004 @subsection How does it work?
4005
4006
4007 When a GNUnet peer needs to send a message to another GNUnet peer that has
4008 advertised (only) an SMTP transport address, GNUnet base64-encodes the
4009 message and sends it in an E-mail to the advertised address. The
4010 advertisement contains a filter which is placed in the E-mail header,
4011 such that the receiving host can filter the tagged E-mails and forward it
4012 to the GNUnet peer process. The filter can be specified individually by
4013 each peer and be changed over time. This makes it impossible to censor
4014 GNUnet E-mail messages by searching for a generic filter.
4015
4016 @node How do I configure my peer?
4017 @subsection How do I configure my peer?
4018
4019
4020 First, you need to configure @code{procmail} to filter your inbound E-mail
4021 for GNUnet traffic. The GNUnet messages must be delivered into a pipe, for
4022 example @code{/tmp/gnunet.smtp}. You also need to define a filter that is
4023 used by @command{procmail} to detect GNUnet messages. You are free to
4024 choose whichever filter you like, but you should make sure that it does
4025 not occur in your other E-mail. In our example, we will use
4026 @code{X-mailer: GNUnet}. The @code{~/.procmailrc} configuration file then
4027 looks like this:
4028
4029 @example
4030 :0:
4031 * ^X-mailer: GNUnet
4032 /tmp/gnunet.smtp
4033 # where do you want your other e-mail delivered to
4034 # (default: /var/spool/mail/)
4035 :0: /var/spool/mail/
4036 @end example
4037
4038 After adding this file, first make sure that your regular E-mail still
4039 works (e.g. by sending an E-mail to yourself). Then edit the GNUnet
4040 configuration. In the section @code{SMTP} you need to specify your E-mail
4041 address under @code{EMAIL}, your mail server (for outgoing mail) under
4042 @code{SERVER}, the filter (X-mailer: GNUnet in the example) under
4043 @code{FILTER} and the name of the pipe under @code{PIPE}.@ The completed
4044 section could then look like this:
4045
4046 @example
4047 EMAIL = me@@mail.gnu.org MTU = 65000 SERVER = mail.gnu.org:25 FILTER =
4048 "X-mailer: GNUnet" PIPE = /tmp/gnunet.smtp
4049 @end example
4050
4051 Finally, you need to add @code{smtp} to the list of @code{TRANSPORTS} in
4052 the @code{GNUNETD} section. GNUnet peers will use the E-mail address that
4053 you specified to contact your peer until the advertisement times out.
4054 Thus, if you are not sure if everything works properly or if you are not
4055 planning to be online for a long time, you may want to configure this
4056 timeout to be short, e.g. just one hour. For this, set
4057 @code{HELLOEXPIRES} to @code{1} in the @code{GNUNETD} section.
4058
4059 This should be it, but you may probably want to test it first.
4060
4061 @node How do I test if it works?
4062 @subsection How do I test if it works?
4063
4064
4065 Any transport can be subjected to some rudimentary tests using the
4066 @code{gnunet-transport-check} tool. The tool sends a message to the local
4067 node via the transport and checks that a valid message is received. While
4068 this test does not involve other peers and can not check if firewalls or
4069 other network obstacles prohibit proper operation, this is a great
4070 testcase for the SMTP transport since it tests pretty much nearly all of
4071 the functionality.
4072
4073 @code{gnunet-transport-check} should only be used without running
4074 @code{gnunetd} at the same time. By default, @code{gnunet-transport-check}
4075 tests all transports that are specified in the configuration file. But
4076 you can specifically test SMTP by giving the option
4077 @code{--transport=smtp}.
4078
4079 Note that this test always checks if a transport can receive and send.
4080 While you can configure most transports to only receive or only send
4081 messages, this test will only work if you have configured the transport
4082 to send and receive messages.
4083
4084 @node How fast is it?
4085 @subsection How fast is it?
4086
4087
4088 We have measured the performance of the UDP, TCP and SMTP transport layer
4089 directly and when used from an application using the GNUnet core.
4090 Measuring just the transport layer gives the better view of the actual
4091 overhead of the protocol, whereas evaluating the transport from the
4092 application puts the overhead into perspective from a practical point of
4093 view.
4094
4095 The loopback measurements of the SMTP transport were performed on three
4096 different machines spanning a range of modern SMTP configurations. We
4097 used a PIII-800 running RedHat 7.3 with the Purdue Computer Science
4098 configuration which includes filters for spam. We also used a Xenon 2 GHZ
4099 with a vanilla RedHat 8.0 sendmail configuration. Furthermore, we used
4100 qmail on a PIII-1000 running Sorcerer GNU Linux (SGL). The numbers for
4101 UDP and TCP are provided using the SGL configuration. The qmail benchmark
4102 uses qmail's internal filtering whereas the sendmail benchmarks relies on
4103 procmail to filter and deliver the mail. We used the transport layer to
4104 send a message of b bytes (excluding transport protocol headers) directly
4105 to the local machine. This way, network latency and packet loss on the
4106 wire have no impact on the timings. n messages were sent sequentially over
4107 the transport layer, sending message i+1 after the i-th message was
4108 received. All messages were sent over the same connection and the time to
4109 establish the connection was not taken into account since this overhead is
4110 minuscule in practice --- as long as a connection is used for a
4111 significant number of messages.
4112
4113 @multitable @columnfractions .20 .15 .15 .15 .15 .15
4114 @headitem Transport @tab UDP @tab TCP @tab SMTP (Purdue sendmail)
4115 @tab SMTP (RH 8.0) @tab SMTP (SGL qmail)
4116 @item  11 bytes @tab 31 ms @tab 55 ms @tab  781 s @tab 77 s @tab 24 s
4117 @item  407 bytes @tab 37 ms @tab 62 ms @tab  789 s @tab 78 s @tab 25 s
4118 @item 1,221 bytes @tab 46 ms @tab 73 ms @tab  804 s @tab 78 s @tab 25 s
4119 @end multitable
4120
4121 The benchmarks show that UDP and TCP are, as expected, both significantly
4122 faster compared with any of the SMTP services. Among the SMTP
4123 implementations, there can be significant differences depending on the
4124 SMTP configuration. Filtering with an external tool like procmail that
4125 needs to re-parse its configuration for each mail can be very expensive.
4126 Applying spam filters can also significantly impact the performance of
4127 the underlying SMTP implementation. The microbenchmark shows that SMTP
4128 can be a viable solution for initiating peer-to-peer sessions: a couple of
4129 seconds to connect to a peer are probably not even going to be noticed by
4130 users. The next benchmark measures the possible throughput for a
4131 transport. Throughput can be measured by sending multiple messages in
4132 parallel and measuring packet loss. Note that not only UDP but also the
4133 TCP transport can actually loose messages since the TCP implementation
4134 drops messages if the @code{write} to the socket would block. While the
4135 SMTP protocol never drops messages itself, it is often so
4136 slow that only a fraction of the messages can be sent and received in the
4137 given time-bounds. For this benchmark we report the message loss after
4138 allowing t time for sending m messages. If messages were not sent (or
4139 received) after an overall timeout of t, they were considered lost. The
4140 benchmark was performed using two Xeon 2 GHZ machines running RedHat 8.0
4141 with sendmail. The machines were connected with a direct 100 MBit Ethernet
4142 connection.@ Figures udp1200, tcp1200 and smtp-MTUs show that the
4143 throughput for messages of size 1,200 octets is 2,343 kbps, 3,310 kbps
4144 and 6 kbps for UDP, TCP and SMTP respectively. The high per-message
4145 overhead of SMTP can be improved by increasing the MTU, for example, an
4146 MTU of 12,000 octets improves the throughput to 13 kbps as figure
4147 smtp-MTUs shows. Our research paper) has some more details on the
4148 benchmarking results.
4149
4150 @cindex Bluetooth plugin
4151 @node Bluetooth plugin
4152 @section Bluetooth plugin
4153
4154
4155 This page describes the new Bluetooth transport plugin for GNUnet. The
4156 plugin is still in the testing stage so don't expect it to work
4157 perfectly. If you have any questions or problems just post them here or
4158 ask on the IRC channel.
4159
4160 @itemize @bullet
4161 @item What do I need to use the Bluetooth plugin transport?
4162 @item BluetoothHow does it work?
4163 @item What possible errors should I be aware of?
4164 @item How do I configure my peer?
4165 @item How can I test it?
4166 @end itemize
4167
4168 @menu
4169 * What do I need to use the Bluetooth plugin transport?::
4170 * How does it work2?::
4171 * What possible errors should I be aware of?::
4172 * How do I configure my peer2?::
4173 * How can I test it?::
4174 * The implementation of the Bluetooth transport plugin::
4175 @end menu
4176
4177 @node What do I need to use the Bluetooth plugin transport?
4178 @subsection What do I need to use the Bluetooth plugin transport?
4179
4180
4181 If you are a GNU/Linux user and you want to use the Bluetooth
4182 transport plugin you should install the
4183 @command{BlueZ development libraries} (if they aren't already
4184 installed).
4185 For instructions about how to install the libraries you should
4186 check out the BlueZ site
4187 (@uref{http://www.bluez.org/, http://www.bluez.org}). If you don't know if
4188 you have the necessary libraries, don't worry, just run the GNUnet
4189 configure script and you will be able to see a notification at the end
4190 which will warn you if you don't have the necessary libraries.
4191
4192 If you are a Windows user you should have installed the
4193 @emph{MinGW}/@emph{MSys2} with the latest updates (especially the
4194 @emph{ws2bth} header). If this is your first build of GNUnet on Windows
4195 you should check out the SBuild repository. It will semi-automatically
4196 assembles a @emph{MinGW}/@emph{MSys2} installation with a lot of extra
4197 packages which are needed for the GNUnet build. So this will ease your
4198 work!@ Finally you just have to be sure that you have the correct drivers
4199 for your Bluetooth device installed and that your device is on and in a
4200 discoverable mode. The Windows Bluetooth Stack supports only the RFCOMM
4201 protocol so we cannot turn on your device programatically!
4202
4203 @c FIXME: Change to unique title
4204 @node How does it work2?
4205 @subsection How does it work2?
4206
4207
4208 The Bluetooth transport plugin uses virtually the same code as the WLAN
4209 plugin and only the helper binary is different. The helper takes a single
4210 argument, which represents the interface name and is specified in the
4211 configuration file. Here are the basic steps that are followed by the
4212 helper binary used on GNU/Linux:
4213
4214 @itemize @bullet
4215 @item it verifies if the name corresponds to a Bluetooth interface name
4216 @item it verifies if the interface is up (if it is not, it tries to bring
4217 it up)
4218 @item it tries to enable the page and inquiry scan in order to make the
4219 device discoverable and to accept incoming connection requests
4220 @emph{The above operations require root access so you should start the
4221 transport plugin with root privileges.}
4222 @item it finds an available port number and registers a SDP service which
4223 will be used to find out on which port number is the server listening on
4224 and switch the socket in listening mode
4225 @item it sends a HELLO message with its address
4226 @item finally it forwards traffic from the reading sockets to the STDOUT
4227 and from the STDIN to the writing socket
4228 @end itemize
4229
4230 Once in a while the device will make an inquiry scan to discover the
4231 nearby devices and it will send them randomly HELLO messages for peer
4232 discovery.
4233
4234 @node What possible errors should I be aware of?
4235 @subsection What possible errors should I be aware of?
4236
4237
4238 @emph{This section is dedicated for GNU/Linux users}
4239
4240 Well there are many ways in which things could go wrong but I will try to
4241 present some tools that you could use to debug and some scenarios.
4242
4243 @itemize @bullet
4244
4245 @item @code{bluetoothd -n -d} : use this command to enable logging in the
4246 foreground and to print the logging messages
4247
4248 @item @code{hciconfig}: can be used to configure the Bluetooth devices.
4249 If you run it without any arguments it will print information about the
4250 state of the interfaces. So if you receive an error that the device
4251 couldn't be brought up you should try to bring it manually and to see if
4252 it works (use @code{hciconfig -a hciX up}). If you can't and the
4253 Bluetooth address has the form 00:00:00:00:00:00 it means that there is
4254 something wrong with the D-Bus daemon or with the Bluetooth daemon. Use
4255 @code{bluetoothd} tool to see the logs
4256
4257 @item @code{sdptool} can be used to control and interrogate SDP servers.
4258 If you encounter problems regarding the SDP server (like the SDP server is
4259 down) you should check out if the D-Bus daemon is running correctly and to
4260 see if the Bluetooth daemon started correctly(use @code{bluetoothd} tool).
4261 Also, sometimes the SDP service could work but somehow the device couldn't
4262 register its service. Use @code{sdptool browse [dev-address]} to see if
4263 the service is registered. There should be a service with the name of the
4264 interface and GNUnet as provider.
4265
4266 @item @code{hcitool} : another useful tool which can be used to configure
4267 the device and to send some particular commands to it.
4268
4269 @item @code{hcidump} : could be used for low level debugging
4270 @end itemize
4271
4272 @c FIXME: A more unique name
4273 @node How do I configure my peer2?
4274 @subsection How do I configure my peer2?
4275
4276
4277 On GNU/Linux, you just have to be sure that the interface name
4278 corresponds to the one that you want to use.
4279 Use the @code{hciconfig} tool to check that.
4280 By default it is set to hci0 but you can change it.
4281
4282 A basic configuration looks like this:
4283
4284 @example
4285 [transport-bluetooth]
4286 # Name of the interface (typically hciX)
4287 INTERFACE = hci0
4288 # Real hardware, no testing
4289 TESTMODE = 0 TESTING_IGNORE_KEYS = ACCEPT_FROM;
4290 @end example
4291
4292 In order to use the Bluetooth transport plugin when the transport service
4293 is started, you must add the plugin name to the default transport service
4294 plugins list. For example:
4295
4296 @example
4297 [transport] ...  PLUGINS = dns bluetooth ...
4298 @end example
4299
4300 If you want to use only the Bluetooth plugin set
4301 @emph{PLUGINS = bluetooth}
4302
4303 On Windows, you cannot specify which device to use. The only thing that
4304 you should do is to add @emph{bluetooth} on the plugins list of the
4305 transport service.
4306
4307 @node How can I test it?
4308 @subsection How can I test it?
4309
4310
4311 If you have two Bluetooth devices on the same machine and you are using
4312 GNU/Linux you must:
4313
4314 @itemize @bullet
4315
4316 @item create two different file configuration (one which will use the
4317 first interface (@emph{hci0}) and the other which will use the second
4318 interface (@emph{hci1})). Let's name them @emph{peer1.conf} and
4319 @emph{peer2.conf}.
4320
4321 @item run @emph{gnunet-peerinfo -c peerX.conf -s} in order to generate the
4322 peers private keys. The @strong{X} must be replace with 1 or 2.
4323
4324 @item run @emph{gnunet-arm -c peerX.conf -s -i=transport} in order to
4325 start the transport service. (Make sure that you have "bluetooth" on the
4326 transport plugins list if the Bluetooth transport service doesn't start.)
4327
4328 @item run @emph{gnunet-peerinfo -c peer1.conf -s} to get the first peer's
4329 ID. If you already know your peer ID (you saved it from the first
4330 command), this can be skipped.
4331
4332 @item run @emph{gnunet-transport -c peer2.conf -p=PEER1_ID -s} to start
4333 sending data for benchmarking to the other peer.
4334
4335 @end itemize
4336
4337
4338 This scenario will try to connect the second peer to the first one and
4339 then start sending data for benchmarking.
4340
4341 On Windows you cannot test the plugin functionality using two Bluetooth
4342 devices from the same machine because after you install the drivers there
4343 will occur some conflicts between the Bluetooth stacks. (At least that is
4344 what happened on my machine : I wasn't able to use the Bluesoleil stack and
4345 the WINDCOMM one in the same time).
4346
4347 If you have two different machines and your configuration files are good
4348 you can use the same scenario presented on the beginning of this section.
4349
4350 Another way to test the plugin functionality is to create your own
4351 application which will use the GNUnet framework with the Bluetooth
4352 transport service.
4353
4354 @node The implementation of the Bluetooth transport plugin
4355 @subsection The implementation of the Bluetooth transport plugin
4356
4357
4358 This page describes the implementation of the Bluetooth transport plugin.
4359
4360 First I want to remind you that the Bluetooth transport plugin uses
4361 virtually the same code as the WLAN plugin and only the helper binary is
4362 different. Also the scope of the helper binary from the Bluetooth
4363 transport plugin is the same as the one used for the WLAN transport
4364 plugin: it accesses the interface and then it forwards traffic in both
4365 directions between the Bluetooth interface and stdin/stdout of the
4366 process involved.
4367
4368 The Bluetooth plugin transport could be used both on GNU/Linux and Windows
4369 platforms.
4370
4371 @itemize @bullet
4372 @item Linux functionality
4373 @item Windows functionality
4374 @item Pending Features
4375 @end itemize
4376
4377
4378
4379 @menu
4380 * Linux functionality::
4381 * THE INITIALIZATION::
4382 * THE LOOP::
4383 * Details about the broadcast implementation::
4384 * Windows functionality::
4385 * Pending features::
4386 @end menu
4387
4388 @node Linux functionality
4389 @subsubsection Linux functionality
4390
4391
4392 In order to implement the plugin functionality on GNU/Linux I
4393 used the BlueZ stack.
4394 For the communication with the other devices I used the RFCOMM
4395 protocol. Also I used the HCI protocol to gain some control over the
4396 device. The helper binary takes a single argument (the name of the
4397 Bluetooth interface) and is separated in two stages:
4398
4399 @c %** 'THE INITIALIZATION' should be in bigger letters or stand out, not
4400 @c %** starting a new section?
4401 @node THE INITIALIZATION
4402 @subsubsection THE INITIALIZATION
4403
4404 @itemize @bullet
4405 @item first, it checks if we have root privileges
4406 (@emph{Remember that we need to have root privileges in order to be able
4407 to bring the interface up if it is down or to change its state.}).
4408
4409 @item second, it verifies if the interface with the given name exists.
4410
4411 @strong{If the interface with that name exists and it is a Bluetooth
4412 interface:}
4413
4414 @item it creates a RFCOMM socket which will be used for listening and call
4415 the @emph{open_device} method
4416
4417 On the @emph{open_device} method:
4418 @itemize @bullet
4419 @item creates a HCI socket used to send control events to the the device
4420 @item searches for the device ID using the interface name
4421 @item saves the device MAC address
4422 @item checks if the interface is down and tries to bring it UP
4423 @item checks if the interface is in discoverable mode and tries to make it
4424 discoverable
4425 @item closes the HCI socket and binds the RFCOMM one
4426 @item switches the RFCOMM socket in listening mode
4427 @item registers the SDP service (the service will be used by the other
4428 devices to get the port on which this device is listening on)
4429 @end itemize
4430
4431 @item drops the root privileges
4432
4433 @strong{If the interface is not a Bluetooth interface the helper exits
4434 with a suitable error}
4435 @end itemize
4436
4437 @c %** Same as for @node entry above
4438 @node THE LOOP
4439 @subsubsection THE LOOP
4440
4441 The helper binary uses a list where it saves all the connected neighbour
4442 devices (@emph{neighbours.devices}) and two buffers (@emph{write_pout} and
4443 @emph{write_std}). The first message which is send is a control message
4444 with the device's MAC address in order to announce the peer presence to
4445 the neighbours. Here are a short description of what happens in the main
4446 loop:
4447
4448 @itemize @bullet
4449 @item Every time when it receives something from the STDIN it processes
4450 the data and saves the message in the first buffer (@emph{write_pout}).
4451 When it has something in the buffer, it gets the destination address from
4452 the buffer, searches the destination address in the list (if there is no
4453 connection with that device, it creates a new one and saves it to the
4454 list) and sends the message.
4455 @item Every time when it receives something on the listening socket it
4456 accepts the connection and saves the socket on a list with the reading
4457 sockets. @item Every time when it receives something from a reading
4458 socket it parses the message, verifies the CRC and saves it in the
4459 @emph{write_std} buffer in order to be sent later to the STDOUT.
4460 @end itemize
4461
4462 So in the main loop we use the select function to wait until one of the
4463 file descriptor saved in one of the two file descriptors sets used is
4464 ready to use. The first set (@emph{rfds}) represents the reading set and
4465 it could contain the list with the reading sockets, the STDIN file
4466 descriptor or the listening socket. The second set (@emph{wfds}) is the
4467 writing set and it could contain the sending socket or the STDOUT file
4468 descriptor. After the select function returns, we check which file
4469 descriptor is ready to use and we do what is supposed to do on that kind
4470 of event. @emph{For example:} if it is the listening socket then we
4471 accept a new connection and save the socket in the reading list; if it is
4472 the STDOUT file descriptor, then we write to STDOUT the message from the
4473 @emph{write_std} buffer.
4474
4475 To find out on which port a device is listening on we connect to the local
4476 SDP server and search the registered service for that device.
4477
4478 @emph{You should be aware of the fact that if the device fails to connect
4479 to another one when trying to send a message it will attempt one more
4480 time. If it fails again, then it skips the message.}
4481 @emph{Also you should know that the transport Bluetooth plugin has
4482 support for @strong{broadcast messages}.}
4483
4484 @node Details about the broadcast implementation
4485 @subsubsection Details about the broadcast implementation
4486
4487
4488 First I want to point out that the broadcast functionality for the CONTROL
4489 messages is not implemented in a conventional way. Since the inquiry scan
4490 time is too big and it will take some time to send a message to all the
4491 discoverable devices I decided to tackle the problem in a different way.
4492 Here is how I did it:
4493
4494 @itemize @bullet
4495 @item If it is the first time when I have to broadcast a message I make an
4496 inquiry scan and save all the devices' addresses to a vector.
4497 @item After the inquiry scan ends I take the first address from the list
4498 and I try to connect to it. If it fails, I try to connect to the next one.
4499 If it succeeds, I save the socket to a list and send the message to the
4500 device.
4501 @item When I have to broadcast another message, first I search on the list
4502 for a new device which I'm not connected to. If there is no new device on
4503 the list I go to the beginning of the list and send the message to the
4504 old devices. After 5 cycles I make a new inquiry scan to check out if
4505 there are new discoverable devices and save them to the list. If there
4506 are no new discoverable devices I reset the cycling counter and go again
4507 through the old list and send messages to the devices saved in it.
4508 @end itemize
4509
4510 @strong{Therefore}:
4511
4512 @itemize @bullet
4513 @item every time when I have a broadcast message I look up on the list
4514 for a new device and send the message to it
4515 @item if I reached the end of the list for 5 times and I'm connected to
4516 all the devices from the list I make a new inquiry scan.
4517 @emph{The number of the list's cycles after an inquiry scan could be
4518 increased by redefining the MAX_LOOPS variable}
4519 @item when there are no new devices I send messages to the old ones.
4520 @end itemize
4521
4522 Doing so, the broadcast control messages will reach the devices but with
4523 delay.
4524
4525 @emph{NOTICE:} When I have to send a message to a certain device first I
4526 check on the broadcast list to see if we are connected to that device. If
4527 not we try to connect to it and in case of success we save the address and
4528 the socket on the list. If we are already connected to that device we
4529 simply use the socket.
4530
4531 @node Windows functionality
4532 @subsubsection Windows functionality
4533
4534
4535 For Windows I decided to use the Microsoft Bluetooth stack which has the
4536 advantage of coming standard from Windows XP SP2. The main disadvantage is
4537 that it only supports the RFCOMM protocol so we will not be able to have
4538 a low level control over the Bluetooth device. Therefore it is the user
4539 responsibility to check if the device is up and in the discoverable mode.
4540 Also there are no tools which could be used for debugging in order to read
4541 the data coming from and going to a Bluetooth device, which obviously
4542 hindered my work. Another thing that slowed down the implementation of the
4543 plugin (besides that I wasn't too accommodated with the win32 API) was that
4544 there were some bugs on MinGW regarding the Bluetooth. Now they are solved
4545 but you should keep in mind that you should have the latest updates
4546 (especially the @emph{ws2bth} header).
4547
4548 Besides the fact that it uses the Windows Sockets, the Windows
4549 implementation follows the same principles as the GNU/Linux one:
4550
4551 @itemize @bullet
4552 @item It has a initalization part where it initializes the
4553 Windows Sockets, creates a RFCOMM socket which will be binded and switched
4554 to the listening mode and registers a SDP service. In the Microsoft
4555 Bluetooth API there are two ways to work with the SDP:
4556 @itemize @bullet
4557 @item an easy way which works with very simple service records
4558 @item a hard way which is useful when you need to update or to delete the
4559 record
4560 @end itemize
4561 @end itemize
4562
4563 Since I only needed the SDP service to find out on which port the device
4564 is listening on and that did not change, I decided to use the easy way.
4565 In order to register the service I used the @emph{WSASetService} function
4566 and I generated the @emph{Universally Unique Identifier} with the
4567 @emph{guidgen.exe} Windows's tool.
4568
4569 In the loop section the only difference from the GNU/Linux implementation
4570 is that I used the @code{GNUNET_NETWORK} library for
4571 functions like @emph{accept}, @emph{bind}, @emph{connect} or
4572 @emph{select}. I decided to use the
4573 @code{GNUNET_NETWORK} library because I also needed to interact
4574 with the STDIN and STDOUT handles and on Windows
4575 the select function is only defined for sockets,
4576 and it will not work for arbitrary file handles.
4577
4578 Another difference between GNU/Linux and Windows implementation is that in
4579 GNU/Linux, the Bluetooth address is represented in 48 bits
4580 while in Windows is represented in 64 bits.
4581 Therefore I had to do some changes on @emph{plugin_transport_wlan} header.
4582
4583 Also, currently on Windows the Bluetooth plugin doesn't have support for
4584 broadcast messages. When it receives a broadcast message it will skip it.
4585
4586 @node Pending features
4587 @subsubsection Pending features
4588
4589
4590 @itemize @bullet
4591 @item Implement the broadcast functionality on Windows @emph{(currently
4592 working on)}
4593 @item Implement a testcase for the helper :@ @emph{The testcase
4594 consists of a program which emulates the plugin and uses the helper. It
4595 will simulate connections, disconnections and data transfers.}
4596 @end itemize
4597
4598 If you have a new idea about a feature of the plugin or suggestions about
4599 how I could improve the implementation you are welcome to comment or to
4600 contact me.
4601
4602 @node WLAN plugin
4603 @section WLAN plugin
4604
4605
4606 This section documents how the wlan transport plugin works. Parts which
4607 are not implemented yet or could be better implemented are described at
4608 the end.
4609
4610 @cindex ATS Subsystem
4611 @node ATS Subsystem
4612 @section ATS Subsystem
4613
4614
4615 ATS stands for "automatic transport selection", and the function of ATS in
4616 GNUnet is to decide on which address (and thus transport plugin) should
4617 be used for two peers to communicate, and what bandwidth limits should be
4618 imposed on such an individual connection. To help ATS make an informed
4619 decision, higher-level services inform the ATS service about their
4620 requirements and the quality of the service rendered. The ATS service
4621 also interacts with the transport service to be appraised of working
4622 addresses and to communicate its resource allocation decisions. Finally,
4623 the ATS service's operation can be observed using a monitoring API.
4624
4625 The main logic of the ATS service only collects the available addresses,
4626 their performance characteristics and the applications requirements, but
4627 does not make the actual allocation decision. This last critical step is
4628 left to an ATS plugin, as we have implemented (currently three) different
4629 allocation strategies which differ significantly in their performance and
4630 maturity, and it is still unclear if any particular plugin is generally
4631 superior.
4632
4633 @cindex CORE Subsystem
4634 @node CORE Subsystem
4635 @section CORE Subsystem
4636
4637
4638 The CORE subsystem in GNUnet is responsible for securing link-layer
4639 communications between nodes in the GNUnet overlay network. CORE builds
4640 on the TRANSPORT subsystem which provides for the actual, insecure,
4641 unreliable link-layer communication (for example, via UDP or WLAN), and
4642 then adds fundamental security to the connections:
4643
4644 @itemize @bullet
4645 @item confidentiality with so-called perfect forward secrecy; we use
4646 ECDHE
4647 (@uref{http://en.wikipedia.org/wiki/Elliptic_curve_Diffie%E2%80%93Hellman, Elliptic-curve Diffie---Hellman})
4648 powered by Curve25519
4649 (@uref{http://cr.yp.to/ecdh.html, Curve25519}) for the key
4650 exchange and then use symmetric encryption, encrypting with both AES-256
4651 (@uref{http://en.wikipedia.org/wiki/Rijndael, AES-256}) and
4652 Twofish (@uref{http://en.wikipedia.org/wiki/Twofish, Twofish})
4653 @item @uref{http://en.wikipedia.org/wiki/Authentication, authentication}
4654 is achieved by signing the ephemeral keys using Ed25519
4655 (@uref{http://ed25519.cr.yp.to/, Ed25519}), a deterministic
4656 variant of ECDSA
4657 (@uref{http://en.wikipedia.org/wiki/ECDSA, ECDSA})
4658 @item integrity protection (using SHA-512
4659 (@uref{http://en.wikipedia.org/wiki/SHA-2, SHA-512}) to do
4660 encrypt-then-MAC
4661 (@uref{http://en.wikipedia.org/wiki/Authenticated_encryption, encrypt-then-MAC}))
4662 @item Replay
4663 (@uref{http://en.wikipedia.org/wiki/Replay_attack, replay})
4664 protection (using nonces, timestamps, challenge-response,
4665 message counters and ephemeral keys)
4666 @item liveness (keep-alive messages, timeout)
4667 @end itemize
4668
4669 @menu
4670 * Limitations::
4671 * When is a peer "connected"?::
4672 * libgnunetcore::
4673 * The CORE Client-Service Protocol::
4674 * The CORE Peer-to-Peer Protocol::
4675 @end menu
4676
4677 @cindex core subsystem limitations
4678 @node Limitations
4679 @subsection Limitations
4680
4681
4682 CORE does not perform
4683 @uref{http://en.wikipedia.org/wiki/Routing, routing}; using CORE it is
4684 only possible to communicate with peers that happen to already be
4685 "directly" connected with each other. CORE also does not have an
4686 API to allow applications to establish such "direct" connections --- for
4687 this, applications can ask TRANSPORT, but TRANSPORT might not be able to
4688 establish a "direct" connection. The TOPOLOGY subsystem is responsible for
4689 trying to keep a few "direct" connections open at all times. Applications
4690 that need to talk to particular peers should use the CADET subsystem, as
4691 it can establish arbitrary "indirect" connections.
4692
4693 Because CORE does not perform routing, CORE must only be used directly by
4694 applications that either perform their own routing logic (such as
4695 anonymous file-sharing) or that do not require routing, for example
4696 because they are based on flooding the network. CORE communication is
4697 unreliable and delivery is possibly out-of-order. Applications that
4698 require reliable communication should use the CADET service. Each
4699 application can only queue one message per target peer with the CORE
4700 service at any time; messages cannot be larger than approximately
4701 63 kilobytes. If messages are small, CORE may group multiple messages
4702 (possibly from different applications) prior to encryption. If permitted
4703 by the application (using the @uref{http://baus.net/on-tcp_cork/, cork}
4704 option), CORE may delay transmissions to facilitate grouping of multiple
4705 small messages. If cork is not enabled, CORE will transmit the message as
4706 soon as TRANSPORT allows it (TRANSPORT is responsible for limiting
4707 bandwidth and congestion control). CORE does not allow flow control;
4708 applications are expected to process messages at line-speed. If flow
4709 control is needed, applications should use the CADET service.
4710
4711 @cindex when is a peer connected
4712 @node When is a peer "connected"?
4713 @subsection When is a peer "connected"?
4714
4715
4716 In addition to the security features mentioned above, CORE also provides
4717 one additional key feature to applications using it, and that is a
4718 limited form of protocol-compatibility checking. CORE distinguishes
4719 between TRANSPORT-level connections (which enable communication with other
4720 peers) and application-level connections. Applications using the CORE API
4721 will (typically) learn about application-level connections from CORE, and
4722 not about TRANSPORT-level connections. When a typical application uses
4723 CORE, it will specify a set of message types
4724 (from @code{gnunet_protocols.h}) that it understands. CORE will then
4725 notify the application about connections it has with other peers if and
4726 only if those applications registered an intersecting set of message
4727 types with their CORE service. Thus, it is quite possible that CORE only
4728 exposes a subset of the established direct connections to a particular
4729 application --- and different applications running above CORE might see
4730 different sets of connections at the same time.
4731
4732 A special case are applications that do not register a handler for any
4733 message type.
4734 CORE assumes that these applications merely want to monitor connections
4735 (or "all" messages via other callbacks) and will notify those applications
4736 about all connections. This is used, for example, by the
4737 @code{gnunet-core} command-line tool to display the active connections.
4738 Note that it is also possible that the TRANSPORT service has more active
4739 connections than the CORE service, as the CORE service first has to
4740 perform a key exchange with connecting peers before exchanging information
4741 about supported message types and notifying applications about the new
4742 connection.
4743
4744 @cindex libgnunetcore
4745 @node libgnunetcore
4746 @subsection libgnunetcore
4747
4748
4749 The CORE API (defined in @file{gnunet_core_service.h}) is the basic
4750 messaging API used by P2P applications built using GNUnet. It provides
4751 applications the ability to send and receive encrypted messages to the
4752 peer's "directly" connected neighbours.
4753
4754 As CORE connections are generally "direct" connections,@ applications must
4755 not assume that they can connect to arbitrary peers this way, as "direct"
4756 connections may not always be possible. Applications using CORE are
4757 notified about which peers are connected. Creating new "direct"
4758 connections must be done using the TRANSPORT API.
4759
4760 The CORE API provides unreliable, out-of-order delivery. While the
4761 implementation tries to ensure timely, in-order delivery, both message
4762 losses and reordering are not detected and must be tolerated by the
4763 application. Most important, the core will NOT perform retransmission if
4764 messages could not be delivered.
4765
4766 Note that CORE allows applications to queue one message per connected
4767 peer. The rate at which each connection operates is influenced by the
4768 preferences expressed by local application as well as restrictions
4769 imposed by the other peer. Local applications can express their
4770 preferences for particular connections using the "performance" API of the
4771 ATS service.
4772
4773 Applications that require more sophisticated transmission capabilities
4774 such as TCP-like behavior, or if you intend to send messages to arbitrary
4775 remote peers, should use the CADET API.
4776
4777 The typical use of the CORE API is to connect to the CORE service using
4778 @code{GNUNET_CORE_connect}, process events from the CORE service (such as
4779 peers connecting, peers disconnecting and incoming messages) and send
4780 messages to connected peers using
4781 @code{GNUNET_CORE_notify_transmit_ready}. Note that applications must
4782 cancel pending transmission requests if they receive a disconnect event
4783 for a peer that had a transmission pending; furthermore, queuing more
4784 than one transmission request per peer per application using the
4785 service is not permitted.
4786
4787 The CORE API also allows applications to monitor all communications of the
4788 peer prior to encryption (for outgoing messages) or after decryption (for
4789 incoming messages). This can be useful for debugging, diagnostics or to
4790 establish the presence of cover traffic (for anonymity). As monitoring
4791 applications are often not interested in the payload, the monitoring
4792 callbacks can be configured to only provide the message headers (including
4793 the message type and size) instead of copying the full data stream to the
4794 monitoring client.
4795
4796 The init callback of the @code{GNUNET_CORE_connect} function is called
4797 with the hash of the public key of the peer. This public key is used to
4798 identify the peer globally in the GNUnet network. Applications are
4799 encouraged to check that the provided hash matches the hash that they are
4800 using (as theoretically the application may be using a different
4801 configuration file with a different private key, which would result in
4802 hard to find bugs).
4803
4804 As with most service APIs, the CORE API isolates applications from crashes
4805 of the CORE service. If the CORE service crashes, the application will see
4806 disconnect events for all existing connections. Once the connections are
4807 re-established, the applications will be receive matching connect events.
4808
4809 @cindex core clinet-service protocol
4810 @node The CORE Client-Service Protocol
4811 @subsection The CORE Client-Service Protocol
4812
4813
4814 This section describes the protocol between an application using the CORE
4815 service (the client) and the CORE service process itself.
4816
4817
4818 @menu
4819 * Setup2::
4820 * Notifications::
4821 * Sending::
4822 @end menu
4823
4824 @node Setup2
4825 @subsubsection Setup2
4826
4827
4828 When a client connects to the CORE service, it first sends a
4829 @code{InitMessage} which specifies options for the connection and a set of
4830 message type values which are supported by the application. The options
4831 bitmask specifies which events the client would like to be notified about.
4832 The options include:
4833
4834 @table @asis
4835 @item GNUNET_CORE_OPTION_NOTHING No notifications
4836 @item GNUNET_CORE_OPTION_STATUS_CHANGE Peers connecting and disconnecting
4837 @item GNUNET_CORE_OPTION_FULL_INBOUND All inbound messages (after
4838 decryption) with full payload
4839 @item GNUNET_CORE_OPTION_HDR_INBOUND Just the @code{MessageHeader}
4840 of all inbound messages
4841 @item GNUNET_CORE_OPTION_FULL_OUTBOUND All outbound
4842 messages (prior to encryption) with full payload
4843 @item GNUNET_CORE_OPTION_HDR_OUTBOUND Just the @code{MessageHeader} of all
4844 outbound messages
4845 @end table
4846
4847 Typical applications will only monitor for connection status changes.
4848
4849 The CORE service responds to the @code{InitMessage} with an
4850 @code{InitReplyMessage} which contains the peer's identity. Afterwards,
4851 both CORE and the client can send messages.
4852
4853 @node Notifications
4854 @subsubsection Notifications
4855
4856
4857 The CORE will send @code{ConnectNotifyMessage}s and
4858 @code{DisconnectNotifyMessage}s whenever peers connect or disconnect from
4859 the CORE (assuming their type maps overlap with the message types
4860 registered by the client). When the CORE receives a message that matches
4861 the set of message types specified during the @code{InitMessage} (or if
4862 monitoring is enabled in for inbound messages in the options), it sends a
4863 @code{NotifyTrafficMessage} with the peer identity of the sender and the
4864 decrypted payload. The same message format (except with
4865 @code{GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND} for the message type) is
4866 used to notify clients monitoring outbound messages; here, the peer
4867 identity given is that of the receiver.
4868
4869 @node Sending
4870 @subsubsection Sending
4871
4872
4873 When a client wants to transmit a message, it first requests a
4874 transmission slot by sending a @code{SendMessageRequest} which specifies
4875 the priority, deadline and size of the message. Note that these values
4876 may be ignored by CORE. When CORE is ready for the message, it answers
4877 with a @code{SendMessageReady} response. The client can then transmit the
4878 payload with a @code{SendMessage} message. Note that the actual message
4879 size in the @code{SendMessage} is allowed to be smaller than the size in
4880 the original request. A client may at any time send a fresh
4881 @code{SendMessageRequest}, which then superceeds the previous
4882 @code{SendMessageRequest}, which is then no longer valid. The client can
4883 tell which @code{SendMessageRequest} the CORE service's
4884 @code{SendMessageReady} message is for as all of these messages contain a
4885 "unique" request ID (based on a counter incremented by the client
4886 for each request).
4887
4888 @cindex CORE Peer-to-Peer Protocol
4889 @node The CORE Peer-to-Peer Protocol
4890 @subsection The CORE Peer-to-Peer Protocol
4891
4892
4893
4894 @menu
4895 * Creating the EphemeralKeyMessage::
4896 * Establishing a connection::
4897 * Encryption and Decryption::
4898 * Type maps::
4899 @end menu
4900
4901 @cindex EphemeralKeyMessage creation
4902 @node Creating the EphemeralKeyMessage
4903 @subsubsection Creating the EphemeralKeyMessage
4904
4905
4906 When the CORE service starts, each peer creates a fresh ephemeral (ECC)
4907 public-private key pair and signs the corresponding
4908 @code{EphemeralKeyMessage} with its long-term key (which we usually call
4909 the peer's identity; the hash of the public long term key is what results
4910 in a @code{struct GNUNET_PeerIdentity} in all GNUnet APIs. The ephemeral
4911 key is ONLY used for an ECDHE
4912 (@uref{http://en.wikipedia.org/wiki/Elliptic_curve_Diffie%E2%80%93Hellman, Elliptic-curve Diffie---Hellman})
4913 exchange by the CORE service to establish symmetric session keys. A peer
4914 will use the same @code{EphemeralKeyMessage} for all peers for
4915 @code{REKEY_FREQUENCY}, which is usually 12 hours. After that time, it
4916 will create a fresh ephemeral key (forgetting the old one) and broadcast
4917 the new @code{EphemeralKeyMessage} to all connected peers, resulting in
4918 fresh symmetric session keys. Note that peers independently decide on
4919 when to discard ephemeral keys; it is not a protocol violation to discard
4920 keys more often. Ephemeral keys are also never stored to disk; restarting
4921 a peer will thus always create a fresh ephemeral key. The use of ephemeral
4922 keys is what provides @uref{http://en.wikipedia.org/wiki/Forward_secrecy, forward secrecy}.
4923
4924 Just before transmission, the @code{EphemeralKeyMessage} is patched to
4925 reflect the current sender_status, which specifies the current state of
4926 the connection from the point of view of the sender. The possible values
4927 are:
4928
4929 @itemize @bullet
4930 @item @code{KX_STATE_DOWN} Initial value, never used on the network
4931 @item @code{KX_STATE_KEY_SENT} We sent our ephemeral key, do not know the
4932 key of the other peer
4933 @item @code{KX_STATE_KEY_RECEIVED} This peer has received a valid
4934 ephemeral key of the other peer, but we are waiting for the other peer to
4935 confirm it's authenticity (ability to decode) via challenge-response.
4936 @item @code{KX_STATE_UP} The connection is fully up from the point of
4937 view of the sender (now performing keep-alives)
4938 @item @code{KX_STATE_REKEY_SENT} The sender has initiated a rekeying
4939 operation; the other peer has so far failed to confirm a working
4940 connection using the new ephemeral key
4941 @end itemize
4942
4943 @node Establishing a connection
4944 @subsubsection Establishing a connection
4945
4946
4947 Peers begin their interaction by sending a @code{EphemeralKeyMessage} to
4948 the other peer once the TRANSPORT service notifies the CORE service about
4949 the connection.
4950 A peer receiving an @code{EphemeralKeyMessage} with a status
4951 indicating that the sender does not have the receiver's ephemeral key, the
4952 receiver's @code{EphemeralKeyMessage} is sent in response.
4953 Additionally, if the receiver has not yet confirmed the authenticity of
4954 the sender, it also sends an (encrypted)@code{PingMessage} with a
4955 challenge (and the identity of the target) to the other peer. Peers
4956 receiving a @code{PingMessage} respond with an (encrypted)
4957 @code{PongMessage} which includes the challenge. Peers receiving a
4958 @code{PongMessage} check the challenge, and if it matches set the
4959 connection to @code{KX_STATE_UP}.
4960
4961 @node Encryption and Decryption
4962 @subsubsection Encryption and Decryption
4963
4964
4965 All functions related to the key exchange and encryption/decryption of
4966 messages can be found in @file{gnunet-service-core_kx.c} (except for the
4967 cryptographic primitives, which are in @file{util/crypto*.c}).
4968 Given the key material from ECDHE, a Key derivation function
4969 (@uref{https://en.wikipedia.org/wiki/Key_derivation_function, Key derivation function})
4970 is used to derive two pairs of encryption and decryption keys for AES-256
4971 and TwoFish, as well as initialization vectors and authentication keys
4972 (for HMAC
4973 (@uref{https://en.wikipedia.org/wiki/HMAC, HMAC})).
4974 The HMAC is computed over the encrypted payload.
4975 Encrypted messages include an iv_seed and the HMAC in the header.
4976
4977 Each encrypted message in the CORE service includes a sequence number and
4978 a timestamp in the encrypted payload. The CORE service remembers the
4979 largest observed sequence number and a bit-mask which represents which of
4980 the previous 32 sequence numbers were already used.
4981 Messages with sequence numbers lower than the largest observed sequence
4982 number minus 32 are discarded. Messages with a timestamp that is less
4983 than @code{REKEY_TOLERANCE} off (5 minutes) are also discarded. This of
4984 course means that system clocks need to be reasonably synchronized for
4985 peers to be able to communicate. Additionally, as the ephemeral key
4986 changes every 12 hours, a peer would not even be able to decrypt messages
4987 older than 12 hours.
4988
4989 @node Type maps
4990 @subsubsection Type maps
4991
4992
4993 Once an encrypted connection has been established, peers begin to exchange
4994 type maps. Type maps are used to allow the CORE service to determine which
4995 (encrypted) connections should be shown to which applications. A type map
4996 is an array of 65536 bits representing the different types of messages
4997 understood by applications using the CORE service. Each CORE service
4998 maintains this map, simply by setting the respective bit for each message
4999 type supported by any of the applications using the CORE service. Note
5000 that bits for message types embedded in higher-level protocols (such as
5001 MESH) will not be included in these type maps.
5002
5003 Typically, the type map of a peer will be sparse. Thus, the CORE service
5004 attempts to compress its type map using @code{gzip}-style compression
5005 ("deflate") prior to transmission. However, if the compression fails to
5006 compact the map, the map may also be transmitted without compression
5007 (resulting in @code{GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP} or
5008 @code{GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP} messages respectively).
5009 Upon receiving a type map, the respective CORE service notifies
5010 applications about the connection to the other peer if they support any
5011 message type indicated in the type map (or no message type at all).
5012 If the CORE service experience a connect or disconnect event from an
5013 application, it updates its type map (setting or unsetting the respective
5014 bits) and notifies its neighbours about the change.
5015 The CORE services of the neighbours then in turn generate connect and
5016 disconnect events for the peer that sent the type map for their respective
5017 applications. As CORE messages may be lost, the CORE service confirms
5018 receiving a type map by sending back a
5019 @code{GNUNET_MESSAGE_TYPE_CORE_CONFIRM_TYPE_MAP}. If such a confirmation
5020 (with the correct hash of the type map) is not received, the sender will
5021 retransmit the type map (with exponential back-off).
5022
5023 @cindex CADET Subsystem
5024 @cindex CADET
5025 @cindex cadet
5026 @node CADET Subsystem
5027 @section CADET Subsystem
5028
5029 The CADET subsystem in GNUnet is responsible for secure end-to-end
5030 communications between nodes in the GNUnet overlay network. CADET builds
5031 on the CORE subsystem which provides for the link-layer communication and
5032 then adds routing, forwarding and additional security to the connections.
5033 CADET offers the same cryptographic services as CORE, but on an
5034 end-to-end level. This is done so peers retransmitting traffic on behalf
5035 of other peers cannot access the payload data.
5036
5037 @itemize @bullet
5038 @item CADET provides confidentiality with so-called perfect forward
5039 secrecy; we use ECDHE powered by Curve25519 for the key exchange and then
5040 use symmetric encryption, encrypting with both AES-256 and Twofish
5041 @item authentication is achieved by signing the ephemeral keys using
5042 Ed25519, a deterministic variant of ECDSA
5043 @item integrity protection (using SHA-512 to do encrypt-then-MAC, although
5044 only 256 bits are sent to reduce overhead)
5045 @item replay protection (using nonces, timestamps, challenge-response,
5046 message counters and ephemeral keys)
5047 @item liveness (keep-alive messages, timeout)
5048 @end itemize
5049
5050 Additional to the CORE-like security benefits, CADET offers other
5051 properties that make it a more universal service than CORE.
5052
5053 @itemize @bullet
5054 @item CADET can establish channels to arbitrary peers in GNUnet. If a
5055 peer is not immediately reachable, CADET will find a path through the
5056 network and ask other peers to retransmit the traffic on its behalf.
5057 @item CADET offers (optional) reliability mechanisms. In a reliable
5058 channel traffic is guaranteed to arrive complete, unchanged and in-order.
5059 @item CADET takes care of flow and congestion control mechanisms, not
5060 allowing the sender to send more traffic than the receiver or the network
5061 are able to process.
5062 @end itemize
5063
5064 @menu
5065 * libgnunetcadet::
5066 @end menu
5067
5068 @cindex libgnunetcadet
5069 @node libgnunetcadet
5070 @subsection libgnunetcadet
5071
5072
5073 The CADET API (defined in @file{gnunet_cadet_service.h}) is the
5074 messaging API used by P2P applications built using GNUnet.
5075 It provides applications the ability to send and receive encrypted
5076 messages to any peer participating in GNUnet.
5077 The API is heavily base on the CORE API.
5078
5079 CADET delivers messages to other peers in "channels".
5080 A channel is a permanent connection defined by a destination peer
5081 (identified by its public key) and a port number.
5082 Internally, CADET tunnels all channels towards a destination peer
5083 using one session key and relays the data on multiple "connections",
5084 independent from the channels.
5085
5086 Each channel has optional parameters, the most important being the
5087 reliability flag.
5088 Should a message get lost on TRANSPORT/CORE level, if a channel is
5089 created with as reliable, CADET will retransmit the lost message and
5090 deliver it in order to the destination application.
5091
5092 @pindex GNUNET_CADET_connect
5093 To communicate with other peers using CADET, it is necessary to first
5094 connect to the service using @code{GNUNET_CADET_connect}.
5095 This function takes several parameters in form of callbacks, to allow the
5096 client to react to various events, like incoming channels or channels that
5097 terminate, as well as specify a list of ports the client wishes to listen
5098 to (at the moment it is not possible to start listening on further ports
5099 once connected, but nothing prevents a client to connect several times to
5100 CADET, even do one connection per listening port).
5101 The function returns a handle which has to be used for any further
5102 interaction with the service.
5103
5104 @pindex GNUNET_CADET_channel_create
5105 To connect to a remote peer, a client has to call the
5106 @code{GNUNET_CADET_channel_create} function. The most important parameters
5107 given are the remote peer's identity (it public key) and a port, which
5108 specifies which application on the remote peer to connect to, similar to
5109 TCP/UDP ports. CADET will then find the peer in the GNUnet network and
5110 establish the proper low-level connections and do the necessary key
5111 exchanges to assure and authenticated, secure and verified communication.
5112 Similar to @code{GNUNET_CADET_connect},@code{GNUNET_CADET_create_channel}
5113 returns a handle to interact with the created channel.
5114
5115 @pindex GNUNET_CADET_notify_transmit_ready
5116 For every message the client wants to send to the remote application,
5117 @code{GNUNET_CADET_notify_transmit_ready} must be called, indicating the
5118 channel on which the message should be sent and the size of the message
5119 (but not the message itself!). Once CADET is ready to send the message,
5120 the provided callback will fire, and the message contents are provided to
5121 this callback.
5122
5123 Please note the CADET does not provide an explicit notification of when a
5124 channel is connected. In loosely connected networks, like big wireless
5125 mesh networks, this can take several seconds, even minutes in the worst
5126 case. To be alerted when a channel is online, a client can call
5127 @code{GNUNET_CADET_notify_transmit_ready} immediately after
5128 @code{GNUNET_CADET_create_channel}. When the callback is activated, it
5129 means that the channel is online. The callback can give 0 bytes to CADET
5130 if no message is to be sent, this is OK.
5131
5132 @pindex GNUNET_CADET_notify_transmit_cancel
5133 If a transmission was requested but before the callback fires it is no
5134 longer needed, it can be canceled with
5135 @code{GNUNET_CADET_notify_transmit_ready_cancel}, which uses the handle
5136 given back by @code{GNUNET_CADET_notify_transmit_ready}.
5137 As in the case of CORE, only one message can be requested at a time: a
5138 client must not call @code{GNUNET_CADET_notify_transmit_ready} again until
5139 the callback is called or the request is canceled.
5140
5141 @pindex GNUNET_CADET_channel_destroy
5142 When a channel is no longer needed, a client can call
5143 @code{GNUNET_CADET_channel_destroy} to get rid of it.
5144 Note that CADET will try to transmit all pending traffic before notifying
5145 the remote peer of the destruction of the channel, including
5146 retransmitting lost messages if the channel was reliable.
5147
5148 Incoming channels, channels being closed by the remote peer, and traffic
5149 on any incoming or outgoing channels are given to the client when CADET
5150 executes the callbacks given to it at the time of
5151 @code{GNUNET_CADET_connect}.
5152
5153 @pindex GNUNET_CADET_disconnect
5154 Finally, when an application no longer wants to use CADET, it should call
5155 @code{GNUNET_CADET_disconnect}, but first all channels and pending
5156 transmissions must be closed (otherwise CADET will complain).
5157
5158 @cindex NSE Subsystem
5159 @node NSE Subsystem
5160 @section NSE Subsystem
5161
5162
5163 NSE stands for @dfn{Network Size Estimation}. The NSE subsystem provides
5164 other subsystems and users with a rough estimate of the number of peers
5165 currently participating in the GNUnet overlay.
5166 The computed value is not a precise number as producing a precise number
5167 in a decentralized, efficient and secure way is impossible.
5168 While NSE's estimate is inherently imprecise, NSE also gives the expected
5169 range. For a peer that has been running in a stable network for a
5170 while, the real network size will typically (99.7% of the time) be in the
5171 range of [2/3 estimate, 3/2 estimate]. We will now give an overview of the
5172 algorithm used to calculate the estimate;
5173 all of the details can be found in this technical report.
5174
5175 @c FIXME: link to the report.
5176
5177 @menu
5178 * Motivation::
5179 * Principle::
5180 * libgnunetnse::
5181 * The NSE Client-Service Protocol::
5182 * The NSE Peer-to-Peer Protocol::
5183 @end menu
5184
5185 @node Motivation
5186 @subsection Motivation
5187
5188
5189 Some subsystems, like DHT, need to know the size of the GNUnet network to
5190 optimize some parameters of their own protocol. The decentralized nature
5191 of GNUnet makes efficient and securely counting the exact number of peers
5192 infeasible. Although there are several decentralized algorithms to count
5193 the number of peers in a system, so far there is none to do so securely.
5194 Other protocols may allow any malicious peer to manipulate the final
5195 result or to take advantage of the system to perform
5196 @dfn{Denial of Service} (DoS) attacks against the network.
5197 GNUnet's NSE protocol avoids these drawbacks.
5198
5199
5200
5201 @menu
5202 * Security::
5203 @end menu
5204
5205 @cindex NSE security
5206 @cindex nse security
5207 @node Security
5208 @subsubsection Security
5209
5210
5211 The NSE subsystem is designed to be resilient against these attacks.
5212 It uses @uref{http://en.wikipedia.org/wiki/Proof-of-work_system, proofs of work}
5213 to prevent one peer from impersonating a large number of participants,
5214 which would otherwise allow an adversary to artificially inflate the
5215 estimate.
5216 The DoS protection comes from the time-based nature of the protocol:
5217 the estimates are calculated periodically and out-of-time traffic is
5218 either ignored or stored for later retransmission by benign peers.
5219 In particular, peers cannot trigger global network communication at will.
5220
5221 @cindex NSE principle
5222 @cindex nse principle
5223 @node Principle
5224 @subsection Principle
5225
5226
5227 The algorithm calculates the estimate by finding the globally closest
5228 peer ID to a random, time-based value.
5229
5230 The idea is that the closer the ID is to the random value, the more
5231 "densely packed" the ID space is, and therefore, more peers are in the
5232 network.
5233
5234
5235
5236 @menu
5237 * Example::
5238 * Algorithm::
5239 * Target value::
5240 * Timing::
5241 * Controlled Flooding::
5242 * Calculating the estimate::
5243 @end menu
5244
5245 @node Example
5246 @subsubsection Example
5247
5248
5249 Suppose all peers have IDs between 0 and 100 (our ID space), and the
5250 random value is 42.
5251 If the closest peer has the ID 70 we can imagine that the average
5252 "distance" between peers is around 30 and therefore the are around 3
5253 peers in the whole ID space. On the other hand, if the closest peer has
5254 the ID 44, we can imagine that the space is rather packed with peers,
5255 maybe as much as 50 of them.
5256 Naturally, we could have been rather unlucky, and there is only one peer
5257 and happens to have the ID 44. Thus, the current estimate is calculated
5258 as the average over multiple rounds, and not just a single sample.
5259
5260 @node Algorithm
5261 @subsubsection Algorithm
5262
5263
5264 Given that example, one can imagine that the job of the subsystem is to
5265 efficiently communicate the ID of the closest peer to the target value
5266 to all the other peers, who will calculate the estimate from it.
5267
5268 @node Target value
5269 @subsubsection Target value
5270
5271
5272
5273 The target value itself is generated by hashing the current time, rounded
5274 down to an agreed value. If the rounding amount is 1h (default) and the
5275 time is 12:34:56, the time to hash would be 12:00:00. The process is
5276 repeated each rounding amount (in this example would be every hour).
5277 Every repetition is called a round.
5278
5279 @node Timing
5280 @subsubsection Timing
5281
5282
5283 The NSE subsystem has some timing control to avoid everybody broadcasting
5284 its ID all at one. Once each peer has the target random value, it
5285 compares its own ID to the target and calculates the hypothetical size of
5286 the network if that peer were to be the closest.
5287 Then it compares the hypothetical size with the estimate from the previous
5288 rounds. For each value there is an associated point in the period,
5289 let's call it "broadcast time". If its own hypothetical estimate
5290 is the same as the previous global estimate, its "broadcast time" will be
5291 in the middle of the round. If its bigger it will be earlier and if its
5292 smaller (the most likely case) it will be later. This ensures that the
5293 peers closest to the target value start broadcasting their ID the first.
5294
5295 @node Controlled Flooding
5296 @subsubsection Controlled Flooding
5297
5298
5299
5300 When a peer receives a value, first it verifies that it is closer than the
5301 closest value it had so far, otherwise it answers the incoming message
5302 with a message containing the better value. Then it checks a proof of
5303 work that must be included in the incoming message, to ensure that the
5304 other peer's ID is not made up (otherwise a malicious peer could claim to
5305 have an ID of exactly the target value every round). Once validated, it
5306 compares the broadcast time of the received value with the current time
5307 and if it's not too early, sends the received value to its neighbors.
5308 Otherwise it stores the value until the correct broadcast time comes.
5309 This prevents unnecessary traffic of sub-optimal values, since a better
5310 value can come before the broadcast time, rendering the previous one
5311 obsolete and saving the traffic that would have been used to broadcast it
5312 to the neighbors.
5313
5314 @node Calculating the estimate
5315 @subsubsection Calculating the estimate
5316
5317
5318
5319 Once the closest ID has been spread across the network each peer gets the
5320 exact distance between this ID and the target value of the round and
5321 calculates the estimate with a mathematical formula described in the tech
5322 report. The estimate generated with this method for a single round is not
5323 very precise. Remember the case of the example, where the only peer is the
5324 ID 44 and we happen to generate the target value 42, thinking there are
5325 50 peers in the network. Therefore, the NSE subsystem remembers the last
5326 64 estimates and calculates an average over them, giving a result of which
5327 usually has one bit of uncertainty (the real size could be half of the
5328 estimate or twice as much). Note that the actual network size is
5329 calculated in powers of two of the raw input, thus one bit of uncertainty
5330 means a factor of two in the size estimate.
5331
5332 @cindex libgnunetnse
5333 @node libgnunetnse
5334 @subsection libgnunetnse
5335
5336
5337
5338 The NSE subsystem has the simplest API of all services, with only two
5339 calls: @code{GNUNET_NSE_connect} and @code{GNUNET_NSE_disconnect}.
5340
5341 The connect call gets a callback function as a parameter and this function
5342 is called each time the network agrees on an estimate. This usually is
5343 once per round, with some exceptions: if the closest peer has a late
5344 local clock and starts spreading its ID after everyone else agreed on a
5345 value, the callback might be activated twice in a round, the second value
5346 being always bigger than the first. The default round time is set to
5347 1 hour.
5348
5349 The disconnect call disconnects from the NSE subsystem and the callback
5350 is no longer called with new estimates.
5351
5352
5353
5354 @menu
5355 * Results::
5356 * libgnunetnse - Examples::
5357 @end menu
5358
5359 @node Results
5360 @subsubsection Results
5361
5362
5363
5364 The callback provides two values: the average and the
5365 @uref{http://en.wikipedia.org/wiki/Standard_deviation, standard deviation}
5366 of the last 64 rounds. The values provided by the callback function are
5367 logarithmic, this means that the real estimate numbers can be obtained by
5368 calculating 2 to the power of the given value (2average). From a
5369 statistics point of view this means that:
5370
5371 @itemize @bullet
5372 @item 68% of the time the real size is included in the interval
5373 [(2average-stddev), 2]
5374 @item 95% of the time the real size is included in the interval
5375 [(2average-2*stddev, 2^average+2*stddev]
5376 @item 99.7% of the time the real size is included in the interval
5377 [(2average-3*stddev, 2average+3*stddev]
5378 @end itemize
5379
5380 The expected standard variation for 64 rounds in a network of stable size
5381 is 0.2. Thus, we can say that normally:
5382
5383 @itemize @bullet
5384 @item 68% of the time the real size is in the range [-13%, +15%]
5385 @item 95% of the time the real size is in the range [-24%, +32%]
5386 @item 99.7% of the time the real size is in the range [-34%, +52%]
5387 @end itemize
5388
5389 As said in the introduction, we can be quite sure that usually the real
5390 size is between one third and three times the estimate. This can of
5391 course vary with network conditions.
5392 Thus, applications may want to also consider the provided standard
5393 deviation value, not only the average (in particular, if the standard
5394 variation is very high, the average maybe meaningless: the network size is
5395 changing rapidly).
5396
5397 @node libgnunetnse - Examples
5398 @subsubsection libgnunetnse -Examples
5399
5400
5401
5402 Let's close with a couple examples.
5403
5404 @table @asis
5405
5406 @item Average: 10, std dev: 1 Here the estimate would be
5407 2^10 = 1024 peers. (The range in which we can be 95% sure is:
5408 [2^8, 2^12] = [256, 4096]. We can be very (>99.7%) sure that the network
5409 is not a hundred peers and absolutely sure that it is not a million peers,
5410 but somewhere around a thousand.)
5411
5412 @item Average 22, std dev: 0.2 Here the estimate would be
5413 2^22 = 4 Million peers. (The range in which we can be 99.7% sure
5414 is: [2^21.4, 2^22.6] = [2.8M, 6.3M]. We can be sure that the network size
5415 is around four million, with absolutely way of it being 1 million.)
5416
5417 @end table
5418
5419 To put this in perspective, if someone remembers the LHC Higgs boson
5420 results, were announced with "5 sigma" and "6 sigma" certainties. In this
5421 case a 5 sigma minimum would be 2 million and a 6 sigma minimum,
5422 1.8 million.
5423
5424 @node The NSE Client-Service Protocol
5425 @subsection The NSE Client-Service Protocol
5426
5427
5428
5429 As with the API, the client-service protocol is very simple, only has 2
5430 different messages, defined in @code{src/nse/nse.h}:
5431
5432 @itemize @bullet
5433 @item @code{GNUNET_MESSAGE_TYPE_NSE_START}@ This message has no parameters
5434 and is sent from the client to the service upon connection.
5435 @item @code{GNUNET_MESSAGE_TYPE_NSE_ESTIMATE}@ This message is sent from
5436 the service to the client for every new estimate and upon connection.
5437 Contains a timestamp for the estimate, the average and the standard
5438 deviation for the respective round.
5439 @end itemize
5440
5441 When the @code{GNUNET_NSE_disconnect} API call is executed, the client
5442 simply disconnects from the service, with no message involved.
5443
5444 @cindex NSE Peer-to-Peer Protocol
5445 @node The NSE Peer-to-Peer Protocol
5446 @subsection The NSE Peer-to-Peer Protocol
5447
5448
5449 @pindex GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD
5450 The NSE subsystem only has one message in the P2P protocol, the
5451 @code{GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD} message.
5452
5453 This message key contents are the timestamp to identify the round
5454 (differences in system clocks may cause some peers to send messages way
5455 too early or way too late, so the timestamp allows other peers to
5456 identify such messages easily), the
5457 @uref{http://en.wikipedia.org/wiki/Proof-of-work_system, proof of work}
5458 used to make it difficult to mount a
5459 @uref{http://en.wikipedia.org/wiki/Sybil_attack, Sybil attack}, and the
5460 public key, which is used to verify the signature on the message.
5461
5462 Every peer stores a message for the previous, current and next round. The
5463 messages for the previous and current round are given to peers that
5464 connect to us. The message for the next round is simply stored until our
5465 system clock advances to the next round. The message for the current round
5466 is what we are flooding the network with right now.
5467 At the beginning of each round the peer does the following:
5468
5469 @itemize @bullet
5470 @item calculates its own distance to the target value
5471 @item creates, signs and stores the message for the current round (unless
5472 it has a better message in the "next round" slot which came early in the
5473 previous round)
5474 @item calculates, based on the stored round message (own or received) when
5475 to start flooding it to its neighbors
5476 @end itemize
5477
5478 Upon receiving a message the peer checks the validity of the message
5479 (round, proof of work, signature). The next action depends on the
5480 contents of the incoming message:
5481
5482 @itemize @bullet
5483 @item if the message is worse than the current stored message, the peer
5484 sends the current message back immediately, to stop the other peer from
5485 spreading suboptimal results
5486 @item if the message is better than the current stored message, the peer
5487 stores the new message and calculates the new target time to start
5488 spreading it to its neighbors (excluding the one the message came from)
5489 @item if the message is for the previous round, it is compared to the
5490 message stored in the "previous round slot", which may then be updated
5491 @item if the message is for the next round, it is compared to the message
5492 stored in the "next round slot", which again may then be updated
5493 @end itemize
5494
5495 Finally, when it comes to send the stored message for the current round to
5496 the neighbors there is a random delay added for each neighbor, to avoid
5497 traffic spikes and minimize cross-messages.
5498
5499 @cindex HOSTLIST Subsystem
5500 @node HOSTLIST Subsystem
5501 @section HOSTLIST Subsystem
5502
5503
5504
5505 Peers in the GNUnet overlay network need address information so that they
5506 can connect with other peers. GNUnet uses so called HELLO messages to
5507 store and exchange peer addresses.
5508 GNUnet provides several methods for peers to obtain this information:
5509
5510 @itemize @bullet
5511 @item out-of-band exchange of HELLO messages (manually, using for example
5512 gnunet-peerinfo)
5513 @item HELLO messages shipped with GNUnet (automatic with distribution)
5514 @item UDP neighbor discovery in LAN (IPv4 broadcast, IPv6 multicast)
5515 @item topology gossiping (learning from other peers we already connected
5516 to), and
5517 @item the HOSTLIST daemon covered in this section, which is particularly
5518 relevant for bootstrapping new peers.
5519 @end itemize
5520
5521 New peers have no existing connections (and thus cannot learn from gossip
5522 among peers), may not have other peers in their LAN and might be started
5523 with an outdated set of HELLO messages from the distribution.
5524 In this case, getting new peers to connect to the network requires either
5525 manual effort or the use of a HOSTLIST to obtain HELLOs.
5526
5527 @menu
5528 * HELLOs::
5529 * Overview for the HOSTLIST subsystem::
5530 * Interacting with the HOSTLIST daemon::
5531 * Hostlist security address validation::
5532 * The HOSTLIST daemon::
5533 * The HOSTLIST server::
5534 * The HOSTLIST client::
5535 * Usage::
5536 @end menu
5537
5538 @node HELLOs
5539 @subsection HELLOs
5540
5541
5542
5543 The basic information peers require to connect to other peers are
5544 contained in so called HELLO messages you can think of as a business card.
5545 Besides the identity of the peer (based on the cryptographic public key) a
5546 HELLO message may contain address information that specifies ways to
5547 contact a peer. By obtaining HELLO messages, a peer can learn how to
5548 contact other peers.
5549
5550 @node Overview for the HOSTLIST subsystem
5551 @subsection Overview for the HOSTLIST subsystem
5552
5553
5554
5555 The HOSTLIST subsystem provides a way to distribute and obtain contact
5556 information to connect to other peers using a simple HTTP GET request.
5557 It's implementation is split in three parts, the main file for the daemon
5558 itself (@file{gnunet-daemon-hostlist.c}), the HTTP client used to download
5559 peer information (@file{hostlist-client.c}) and the server component used
5560 to provide this information to other peers (@file{hostlist-server.c}).
5561 The server is basically a small HTTP web server (based on GNU
5562 libmicrohttpd) which provides a list of HELLOs known to the local peer for
5563 download. The client component is basically a HTTP client
5564 (based on libcurl) which can download hostlists from one or more websites.
5565 The hostlist format is a binary blob containing a sequence of HELLO
5566 messages. Note that any HTTP server can theoretically serve a hostlist,
5567 the build-in hostlist server makes it simply convenient to offer this
5568 service.
5569
5570
5571 @menu
5572 * Features::
5573 * HOSTLIST - Limitations::
5574 @end menu
5575
5576 @node Features
5577 @subsubsection Features
5578
5579
5580
5581 The HOSTLIST daemon can:
5582
5583 @itemize @bullet
5584 @item provide HELLO messages with validated addresses obtained from
5585 PEERINFO to download for other peers
5586 @item download HELLO messages and forward these message to the TRANSPORT
5587 subsystem for validation
5588 @item advertises the URL of this peer's hostlist address to other peers
5589 via gossip
5590 @item automatically learn about hostlist servers from the gossip of other
5591 peers
5592 @end itemize
5593
5594 @node HOSTLIST - Limitations
5595 @subsubsection HOSTLIST - Limitations
5596
5597
5598
5599 The HOSTLIST daemon does not:
5600
5601 @itemize @bullet
5602 @item verify the cryptographic information in the HELLO messages
5603 @item verify the address information in the HELLO messages
5604 @end itemize
5605
5606 @node Interacting with the HOSTLIST daemon
5607 @subsection Interacting with the HOSTLIST daemon
5608
5609
5610
5611 The HOSTLIST subsystem is currently implemented as a daemon, so there is
5612 no need for the user to interact with it and therefore there is no
5613 command line tool and no API to communicate with the daemon. In the
5614 future, we can envision changing this to allow users to manually trigger
5615 the download of a hostlist.
5616
5617 Since there is no command line interface to interact with HOSTLIST, the
5618 only way to interact with the hostlist is to use STATISTICS to obtain or
5619 modify information about the status of HOSTLIST:
5620
5621 @example
5622 $ gnunet-statistics -s hostlist
5623 @end example
5624
5625 @noindent
5626 In particular, HOSTLIST includes a @strong{persistent} value in statistics
5627 that specifies when the hostlist server might be queried next. As this
5628 value is exponentially increasing during runtime, developers may want to
5629 reset or manually adjust it. Note that HOSTLIST (but not STATISTICS) needs
5630 to be shutdown if changes to this value are to have any effect on the
5631 daemon (as HOSTLIST does not monitor STATISTICS for changes to the
5632 download frequency).
5633
5634 @node Hostlist security address validation
5635 @subsection Hostlist security address validation
5636
5637
5638
5639 Since information obtained from other parties cannot be trusted without
5640 validation, we have to distinguish between @emph{validated} and
5641 @emph{not validated} addresses. Before using (and so trusting)
5642 information from other parties, this information has to be double-checked
5643 (validated). Address validation is not done by HOSTLIST but by the
5644 TRANSPORT service.
5645
5646 The HOSTLIST component is functionally located between the PEERINFO and
5647 the TRANSPORT subsystem. When acting as a server, the daemon obtains valid
5648 (@emph{validated}) peer information (HELLO messages) from the PEERINFO
5649 service and provides it to other peers. When acting as a client, it
5650 contacts the HOSTLIST servers specified in the configuration, downloads
5651 the (unvalidated) list of HELLO messages and forwards these information
5652 to the TRANSPORT server to validate the addresses.
5653
5654 @cindex HOSTLIST daemon
5655 @node The HOSTLIST daemon
5656 @subsection The HOSTLIST daemon
5657
5658
5659
5660 The hostlist daemon is the main component of the HOSTLIST subsystem. It is
5661 started by the ARM service and (if configured) starts the HOSTLIST client
5662 and server components.
5663
5664 @pindex GNUNET_MESSAGE_TYPE_HOSTLIST_ADVERTISEMENT
5665 If the daemon provides a hostlist itself it can advertise it's own
5666 hostlist to other peers. To do so it sends a
5667 @code{GNUNET_MESSAGE_TYPE_HOSTLIST_ADVERTISEMENT} message to other peers
5668 when they connect to this peer on the CORE level. This hostlist
5669 advertisement message contains the URL to access the HOSTLIST HTTP
5670 server of the sender. The daemon may also subscribe to this type of
5671 message from CORE service, and then forward these kind of message to the
5672 HOSTLIST client. The client then uses all available URLs to download peer
5673 information when necessary.
5674
5675 When starting, the HOSTLIST daemon first connects to the CORE subsystem
5676 and if hostlist learning is enabled, registers a CORE handler to receive
5677 this kind of messages. Next it starts (if configured) the client and
5678 server. It passes pointers to CORE connect and disconnect and receive
5679 handlers where the client and server store their functions, so the daemon
5680 can notify them about CORE events.
5681
5682 To clean up on shutdown, the daemon has a cleaning task, shutting down all
5683 subsystems and disconnecting from CORE.
5684
5685 @cindex HOSTLIST server
5686 @node The HOSTLIST server
5687 @subsection The HOSTLIST server
5688
5689
5690
5691 The server provides a way for other peers to obtain HELLOs. Basically it
5692 is a small web server other peers can connect to and download a list of
5693 HELLOs using standard HTTP; it may also advertise the URL of the hostlist
5694 to other peers connecting on CORE level.
5695
5696
5697 @menu
5698 * The HTTP Server::
5699 * Advertising the URL::
5700 @end menu
5701
5702 @node The HTTP Server
5703 @subsubsection The HTTP Server
5704
5705
5706
5707 During startup, the server starts a web server listening on the port
5708 specified with the HTTPPORT value (default 8080). In addition it connects
5709 to the PEERINFO service to obtain peer information. The HOSTLIST server
5710 uses the GNUNET_PEERINFO_iterate function to request HELLO information for
5711 all peers and adds their information to a new hostlist if they are
5712 suitable (expired addresses and HELLOs without addresses are both not
5713 suitable) and the maximum size for a hostlist is not exceeded
5714 (MAX_BYTES_PER_HOSTLISTS = 500000).
5715 When PEERINFO finishes (with a last NULL callback), the server destroys
5716 the previous hostlist response available for download on the web server
5717 and replaces it with the updated hostlist. The hostlist format is
5718 basically a sequence of HELLO messages (as obtained from PEERINFO) without
5719 any special tokenization. Since each HELLO message contains a size field,
5720 the response can easily be split into separate HELLO messages by the
5721 client.
5722
5723 A HOSTLIST client connecting to the HOSTLIST server will receive the
5724 hostlist as a HTTP response and the the server will terminate the
5725 connection with the result code @code{HTTP 200 OK}.
5726 The connection will be closed immediately if no hostlist is available.
5727
5728 @node Advertising the URL
5729 @subsubsection Advertising the URL
5730
5731
5732
5733 The server also advertises the URL to download the hostlist to other peers
5734 if hostlist advertisement is enabled.
5735 When a new peer connects and has hostlist learning enabled, the server
5736 sends a @code{GNUNET_MESSAGE_TYPE_HOSTLIST_ADVERTISEMENT} message to this
5737 peer using the CORE service.
5738
5739 @cindex HOSTLIST client
5740 @node The HOSTLIST client
5741 @subsection The HOSTLIST client
5742
5743
5744
5745 The client provides the functionality to download the list of HELLOs from
5746 a set of URLs.
5747 It performs a standard HTTP request to the URLs configured and learned
5748 from advertisement messages received from other peers. When a HELLO is
5749 downloaded, the HOSTLIST client forwards the HELLO to the TRANSPORT
5750 service for validation.
5751
5752 The client supports two modes of operation:
5753
5754 @itemize @bullet
5755 @item download of HELLOs (bootstrapping)
5756 @item learning of URLs
5757 @end itemize
5758
5759 @menu
5760 * Bootstrapping::
5761 * Learning::
5762 @end menu
5763
5764 @node Bootstrapping
5765 @subsubsection Bootstrapping
5766
5767
5768
5769 For bootstrapping, it schedules a task to download the hostlist from the
5770 set of known URLs.
5771 The downloads are only performed if the number of current
5772 connections is smaller than a minimum number of connections
5773 (at the moment 4).
5774 The interval between downloads increases exponentially; however, the
5775 exponential growth is limited if it becomes longer than an hour.
5776 At that point, the frequency growth is capped at
5777 (#number of connections * 1h).
5778
5779 Once the decision has been taken to download HELLOs, the daemon chooses a
5780 random URL from the list of known URLs. URLs can be configured in the
5781 configuration or be learned from advertisement messages.
5782 The client uses a HTTP client library (libcurl) to initiate the download
5783 using the libcurl multi interface.
5784 Libcurl passes the data to the callback_download function which
5785 stores the data in a buffer if space is available and the maximum size for
5786 a hostlist download is not exceeded (MAX_BYTES_PER_HOSTLISTS = 500000).
5787 When a full HELLO was downloaded, the HOSTLIST client offers this
5788 HELLO message to the TRANSPORT service for validation.
5789 When the download is finished or failed, statistical information about the
5790 quality of this URL is updated.
5791
5792 @cindex HOSTLIST learning
5793 @node Learning
5794 @subsubsection Learning
5795
5796
5797
5798 The client also manages hostlist advertisements from other peers. The
5799 HOSTLIST daemon forwards @code{GNUNET_MESSAGE_TYPE_HOSTLIST_ADVERTISEMENT}
5800 messages to the client subsystem, which extracts the URL from the message.
5801 Next, a test of the newly obtained URL is performed by triggering a
5802 download from the new URL. If the URL works correctly, it is added to the
5803 list of working URLs.
5804
5805 The size of the list of URLs is restricted, so if an additional server is
5806 added and the list is full, the URL with the worst quality ranking
5807 (determined through successful downloads and number of HELLOs e.g.) is
5808 discarded. During shutdown the list of URLs is saved to a file for
5809 persistance and loaded on startup. URLs from the configuration file are
5810 never discarded.
5811
5812 @node Usage
5813 @subsection Usage
5814
5815
5816
5817 To start HOSTLIST by default, it has to be added to the DEFAULTSERVICES
5818 section for the ARM services. This is done in the default configuration.
5819
5820 For more information on how to configure the HOSTLIST subsystem see the
5821 installation handbook:@
5822 Configuring the hostlist to bootstrap@
5823 Configuring your peer to provide a hostlist
5824
5825 @cindex IDENTITY Subsystem
5826 @node IDENTITY Subsystem
5827 @section IDENTITY Subsystem
5828
5829
5830
5831 Identities of "users" in GNUnet are called egos.
5832 Egos can be used as pseudonyms ("fake names") or be tied to an
5833 organization (for example, "GNU") or even the actual identity of a human.
5834 GNUnet users are expected to have many egos. They might have one tied to
5835 their real identity, some for organizations they manage, and more for
5836 different domains where they want to operate under a pseudonym.
5837
5838 The IDENTITY service allows users to manage their egos. The identity
5839 service manages the private keys egos of the local user; it does not
5840 manage identities of other users (public keys). Public keys for other
5841 users need names to become manageable. GNUnet uses the
5842 @dfn{GNU Name System} (GNS) to give names to other users and manage their
5843 public keys securely. This chapter is about the IDENTITY service,
5844 which is about the management of private keys.
5845
5846 On the network, an ego corresponds to an ECDSA key (over Curve25519,
5847 using RFC 6979, as required by GNS). Thus, users can perform actions
5848 under a particular ego by using (signing with) a particular private key.
5849 Other users can then confirm that the action was really performed by that
5850 ego by checking the signature against the respective public key.
5851
5852 The IDENTITY service allows users to associate a human-readable name with
5853 each ego. This way, users can use names that will remind them of the
5854 purpose of a particular ego.
5855 The IDENTITY service will store the respective private keys and
5856 allows applications to access key information by name.
5857 Users can change the name that is locally (!) associated with an ego.
5858 Egos can also be deleted, which means that the private key will be removed
5859 and it thus will not be possible to perform actions with that ego in the
5860 future.
5861
5862 Additionally, the IDENTITY subsystem can associate service functions with
5863 egos.
5864 For example, GNS requires the ego that should be used for the shorten
5865 zone. GNS will ask IDENTITY for an ego for the "gns-short" service.
5866 The IDENTITY service has a mapping of such service strings to the name of
5867 the ego that the user wants to use for this service, for example
5868 "my-short-zone-ego".
5869
5870 Finally, the IDENTITY API provides access to a special ego, the
5871 anonymous ego. The anonymous ego is special in that its private key is not
5872 really private, but fixed and known to everyone.
5873 Thus, anyone can perform actions as anonymous. This can be useful as with
5874 this trick, code does not have to contain a special case to distinguish
5875 between anonymous and pseudonymous egos.
5876
5877 @menu
5878 * libgnunetidentity::
5879 * The IDENTITY Client-Service Protocol::
5880 @end menu
5881
5882 @cindex libgnunetidentity
5883 @node libgnunetidentity
5884 @subsection libgnunetidentity
5885
5886
5887
5888 @menu
5889 * Connecting to the service::
5890 * Operations on Egos::
5891 * The anonymous Ego::
5892 * Convenience API to lookup a single ego::
5893 * Associating egos with service functions::
5894 @end menu
5895
5896 @node Connecting to the service
5897 @subsubsection Connecting to the service
5898
5899
5900
5901 First, typical clients connect to the identity service using
5902 @code{GNUNET_IDENTITY_connect}. This function takes a callback as a
5903 parameter.
5904 If the given callback parameter is non-null, it will be invoked to notify
5905 the application about the current state of the identities in the system.
5906
5907 @itemize @bullet
5908 @item First, it will be invoked on all known egos at the time of the
5909 connection. For each ego, a handle to the ego and the user's name for the
5910 ego will be passed to the callback. Furthermore, a @code{void **} context
5911 argument will be provided which gives the client the opportunity to
5912 associate some state with the ego.
5913 @item Second, the callback will be invoked with NULL for the ego, the name
5914 and the context. This signals that the (initial) iteration over all egos
5915 has completed.
5916 @item Then, the callback will be invoked whenever something changes about
5917 an ego.
5918 If an ego is renamed, the callback is invoked with the ego handle of the
5919 ego that was renamed, and the new name. If an ego is deleted, the callback
5920 is invoked with the ego handle and a name of NULL. In the deletion case,
5921 the application should also release resources stored in the context.
5922 @item When the application destroys the connection to the identity service
5923 using @code{GNUNET_IDENTITY_disconnect}, the callback is again invoked
5924 with the ego and a name of NULL (equivalent to deletion of the egos).
5925 This should again be used to clean up the per-ego context.
5926 @end itemize
5927
5928 The ego handle passed to the callback remains valid until the callback is
5929 invoked with a name of NULL, so it is safe to store a reference to the
5930 ego's handle.
5931
5932 @node Operations on Egos
5933 @subsubsection Operations on Egos
5934
5935
5936
5937 Given an ego handle, the main operations are to get its associated private
5938 key using @code{GNUNET_IDENTITY_ego_get_private_key} or its associated
5939 public key using @code{GNUNET_IDENTITY_ego_get_public_key}.
5940
5941 The other operations on egos are pretty straightforward.
5942 Using @code{GNUNET_IDENTITY_create}, an application can request the
5943 creation of an ego by specifying the desired name.
5944 The operation will fail if that name is
5945 already in use. Using @code{GNUNET_IDENTITY_rename} the name of an
5946 existing ego can be changed. Finally, egos can be deleted using
5947 @code{GNUNET_IDENTITY_delete}. All of these operations will trigger
5948 updates to the callback given to the @code{GNUNET_IDENTITY_connect}
5949 function of all applications that are connected with the identity service
5950 at the time. @code{GNUNET_IDENTITY_cancel} can be used to cancel the
5951 operations before the respective continuations would be called.
5952 It is not guaranteed that the operation will not be completed anyway,
5953 only the continuation will no longer be called.
5954
5955 @node The anonymous Ego
5956 @subsubsection The anonymous Ego
5957
5958
5959
5960 A special way to obtain an ego handle is to call
5961 @code{GNUNET_IDENTITY_ego_get_anonymous}, which returns an ego for the
5962 "anonymous" user --- anyone knows and can get the private key for this
5963 user, so it is suitable for operations that are supposed to be anonymous
5964 but require signatures (for example, to avoid a special path in the code).
5965 The anonymous ego is always valid and accessing it does not require a
5966 connection to the identity service.
5967
5968 @node Convenience API to lookup a single ego
5969 @subsubsection Convenience API to lookup a single ego
5970
5971
5972 As applications commonly simply have to lookup a single ego, there is a
5973 convenience API to do just that. Use @code{GNUNET_IDENTITY_ego_lookup} to
5974 lookup a single ego by name. Note that this is the user's name for the
5975 ego, not the service function. The resulting ego will be returned via a
5976 callback and will only be valid during that callback. The operation can
5977 be canceled via @code{GNUNET_IDENTITY_ego_lookup_cancel}
5978 (cancellation is only legal before the callback is invoked).
5979
5980 @node Associating egos with service functions
5981 @subsubsection Associating egos with service functions
5982
5983
5984 The @code{GNUNET_IDENTITY_set} function is used to associate a particular
5985 ego with a service function. The name used by the service and the ego are
5986 given as arguments.
5987 Afterwards, the service can use its name to lookup the associated ego
5988 using @code{GNUNET_IDENTITY_get}.
5989
5990 @node The IDENTITY Client-Service Protocol
5991 @subsection The IDENTITY Client-Service Protocol
5992
5993
5994
5995 A client connecting to the identity service first sends a message with
5996 type
5997 @code{GNUNET_MESSAGE_TYPE_IDENTITY_START} to the service. After that, the
5998 client will receive information about changes to the egos by receiving
5999 messages of type @code{GNUNET_MESSAGE_TYPE_IDENTITY_UPDATE}.
6000 Those messages contain the private key of the ego and the user's name of
6001 the ego (or zero bytes for the name to indicate that the ego was deleted).
6002 A special bit @code{end_of_list} is used to indicate the end of the
6003 initial iteration over the identity service's egos.
6004
6005 The client can trigger changes to the egos by sending @code{CREATE},
6006 @code{RENAME} or @code{DELETE} messages.
6007 The CREATE message contains the private key and the desired name.@
6008 The RENAME message contains the old name and the new name.@
6009 The DELETE message only needs to include the name of the ego to delete.@
6010 The service responds to each of these messages with a @code{RESULT_CODE}
6011 message which indicates success or error of the operation, and possibly
6012 a human-readable error message.
6013
6014 Finally, the client can bind the name of a service function to an ego by
6015 sending a @code{SET_DEFAULT} message with the name of the service function
6016 and the private key of the ego.
6017 Such bindings can then be resolved using a @code{GET_DEFAULT} message,
6018 which includes the name of the service function. The identity service
6019 will respond to a GET_DEFAULT request with a SET_DEFAULT message
6020 containing the respective information, or with a RESULT_CODE to
6021 indicate an error.
6022
6023 @cindex NAMESTORE Subsystem
6024 @node NAMESTORE Subsystem
6025 @section NAMESTORE Subsystem
6026
6027 The NAMESTORE subsystem provides persistent storage for local GNS zone
6028 information. All local GNS zone information are managed by NAMESTORE. It
6029 provides both the functionality to administer local GNS information (e.g.
6030 delete and add records) as well as to retrieve GNS information (e.g to
6031 list name information in a client).
6032 NAMESTORE does only manage the persistent storage of zone information
6033 belonging to the user running the service: GNS information from other
6034 users obtained from the DHT are stored by the NAMECACHE subsystem.
6035
6036 NAMESTORE uses a plugin-based database backend to store GNS information
6037 with good performance. Here sqlite, MySQL and PostgreSQL are supported
6038 database backends.
6039 NAMESTORE clients interact with the IDENTITY subsystem to obtain
6040 cryptographic information about zones based on egos as described with the
6041 IDENTITY subsystem, but internally NAMESTORE refers to zones using the
6042 ECDSA private key.
6043 In addition, it collaborates with the NAMECACHE subsystem and
6044 stores zone information when local information are modified in the
6045 GNS cache to increase look-up performance for local information.
6046
6047 NAMESTORE provides functionality to look-up and store records, to iterate
6048 over a specific or all zones and to monitor zones for changes. NAMESTORE
6049 functionality can be accessed using the NAMESTORE api or the NAMESTORE
6050 command line tool.
6051
6052 @menu
6053 * libgnunetnamestore::
6054 @end menu
6055
6056 @cindex libgnunetnamestore
6057 @node libgnunetnamestore
6058 @subsection libgnunetnamestore
6059
6060 To interact with NAMESTORE clients first connect to the NAMESTORE service
6061 using the @code{GNUNET_NAMESTORE_connect} passing a configuration handle.
6062 As a result they obtain a NAMESTORE handle, they can use for operations,
6063 or NULL is returned if the connection failed.
6064
6065 To disconnect from NAMESTORE, clients use
6066 @code{GNUNET_NAMESTORE_disconnect} and specify the handle to disconnect.
6067
6068 NAMESTORE internally uses the ECDSA private key to refer to zones. These
6069 private keys can be obtained from the IDENTITY subsytem.
6070 Here @emph{egos} @emph{can be used to refer to zones or the default ego
6071 assigned to the GNS subsystem can be used to obtained the master zone's
6072 private key.}
6073
6074
6075 @menu
6076 * Editing Zone Information::
6077 * Iterating Zone Information::
6078 * Monitoring Zone Information::
6079 @end menu
6080
6081 @node Editing Zone Information
6082 @subsubsection Editing Zone Information
6083
6084
6085
6086 NAMESTORE provides functions to lookup records stored under a label in a
6087 zone and to store records under a label in a zone.
6088
6089 To store (and delete) records, the client uses the
6090 @code{GNUNET_NAMESTORE_records_store} function and has to provide
6091 namestore handle to use, the private key of the zone, the label to store
6092 the records under, the records and number of records plus an callback
6093 function.
6094 After the operation is performed NAMESTORE will call the provided
6095 callback function with the result GNUNET_SYSERR on failure
6096 (including timeout/queue drop/failure to validate), GNUNET_NO if content
6097 was already there or not found GNUNET_YES (or other positive value) on
6098 success plus an additional error message.
6099
6100 Records are deleted by using the store command with 0 records to store.
6101 It is important to note, that records are not merged when records exist
6102 with the label.
6103 So a client has first to retrieve records, merge with existing records
6104 and then store the result.
6105
6106 To perform a lookup operation, the client uses the
6107 @code{GNUNET_NAMESTORE_records_store} function. Here it has to pass the
6108 namestore handle, the private key of the zone and the label. It also has
6109 to provide a callback function which will be called with the result of
6110 the lookup operation:
6111 the zone for the records, the label, and the records including the
6112 number of records included.
6113
6114 A special operation is used to set the preferred nickname for a zone.
6115 This nickname is stored with the zone and is automatically merged with
6116 all labels and records stored in a zone. Here the client uses the
6117 @code{GNUNET_NAMESTORE_set_nick} function and passes the private key of
6118 the zone, the nickname as string plus a the callback with the result of
6119 the operation.
6120
6121 @node Iterating Zone Information
6122 @subsubsection Iterating Zone Information
6123
6124
6125
6126 A client can iterate over all information in a zone or all zones managed
6127 by NAMESTORE.
6128 Here a client uses the @code{GNUNET_NAMESTORE_zone_iteration_start}
6129 function and passes the namestore handle, the zone to iterate over and a
6130 callback function to call with the result.
6131 If the client wants to iterate over all the WHAT!? FIXME, it passes NULL for the zone.
6132 A @code{GNUNET_NAMESTORE_ZoneIterator} handle is returned to be used to
6133 continue iteration.
6134
6135 NAMESTORE calls the callback for every result and expects the client to
6136 call @code{GNUNET_NAMESTORE_zone_iterator_next} to continue to iterate or
6137 @code{GNUNET_NAMESTORE_zone_iterator_stop} to interrupt the iteration.
6138 When NAMESTORE reached the last item it will call the callback with a
6139 NULL value to indicate.
6140
6141 @node Monitoring Zone Information
6142 @subsubsection Monitoring Zone Information
6143
6144
6145
6146 Clients can also monitor zones to be notified about changes. Here the
6147 clients uses the @code{GNUNET_NAMESTORE_zone_monitor_start} function and
6148 passes the private key of the zone and and a callback function to call
6149 with updates for a zone.
6150 The client can specify to obtain zone information first by iterating over
6151 the zone and specify a synchronization callback to be called when the
6152 client and the namestore are synced.
6153
6154 On an update, NAMESTORE will call the callback with the private key of the
6155 zone, the label and the records and their number.
6156
6157 To stop monitoring, the client calls
6158 @code{GNUNET_NAMESTORE_zone_monitor_stop} and passes the handle obtained
6159 from the function to start the monitoring.
6160
6161 @cindex PEERINFO Subsystem
6162 @node PEERINFO Subsystem
6163 @section PEERINFO Subsystem
6164
6165
6166
6167 The PEERINFO subsystem is used to store verified (validated) information
6168 about known peers in a persistent way. It obtains these addresses for
6169 example from TRANSPORT service which is in charge of address validation.
6170 Validation means that the information in the HELLO message are checked by
6171 connecting to the addresses and performing a cryptographic handshake to
6172 authenticate the peer instance stating to be reachable with these
6173 addresses.
6174 Peerinfo does not validate the HELLO messages itself but only stores them
6175 and gives them to interested clients.
6176
6177 As future work, we think about moving from storing just HELLO messages to
6178 providing a generic persistent per-peer information store.
6179 More and more subsystems tend to need to store per-peer information in
6180 persistent way.
6181 To not duplicate this functionality we plan to provide a PEERSTORE
6182 service providing this functionality.
6183
6184 @menu
6185 * PEERINFO - Features::
6186 * PEERINFO - Limitations::
6187 * DeveloperPeer Information::
6188 * Startup::
6189 * Managing Information::
6190 * Obtaining Information::
6191 * The PEERINFO Client-Service Protocol::
6192 * libgnunetpeerinfo::
6193 @end menu
6194
6195 @node PEERINFO - Features
6196 @subsection PEERINFO - Features
6197
6198
6199
6200 @itemize @bullet
6201 @item Persistent storage
6202 @item Client notification mechanism on update
6203 @item Periodic clean up for expired information
6204 @item Differentiation between public and friend-only HELLO
6205 @end itemize
6206
6207 @node PEERINFO - Limitations
6208 @subsection PEERINFO - Limitations
6209
6210
6211 @itemize @bullet
6212 @item Does not perform HELLO validation
6213 @end itemize
6214
6215 @node DeveloperPeer Information
6216 @subsection DeveloperPeer Information
6217
6218
6219
6220 The PEERINFO subsystem stores these information in the form of HELLO
6221 messages you can think of as business cards.
6222 These HELLO messages contain the public key of a peer and the addresses
6223 a peer can be reached under.
6224 The addresses include an expiration date describing how long they are
6225 valid. This information is updated regularly by the TRANSPORT service by
6226 revalidating the address.
6227 If an address is expired and not renewed, it can be removed from the
6228 HELLO message.
6229
6230 Some peer do not want to have their HELLO messages distributed to other
6231 peers, especially when GNUnet's friend-to-friend modus is enabled.
6232 To prevent this undesired distribution. PEERINFO distinguishes between
6233 @emph{public} and @emph{friend-only} HELLO messages.
6234 Public HELLO messages can be freely distributed to other (possibly
6235 unknown) peers (for example using the hostlist, gossiping, broadcasting),
6236 whereas friend-only HELLO messages may not be distributed to other peers.
6237 Friend-only HELLO messages have an additional flag @code{friend_only} set
6238 internally. For public HELLO message this flag is not set.
6239 PEERINFO does and cannot not check if a client is allowed to obtain a
6240 specific HELLO type.
6241
6242 The HELLO messages can be managed using the GNUnet HELLO library.
6243 Other GNUnet systems can obtain these information from PEERINFO and use
6244 it for their purposes.
6245 Clients are for example the HOSTLIST component providing these
6246 information to other peers in form of a hostlist or the TRANSPORT
6247 subsystem using these information to maintain connections to other peers.
6248
6249 @node Startup
6250 @subsection Startup
6251
6252
6253
6254 During startup the PEERINFO services loads persistent HELLOs from disk.
6255 First PEERINFO parses the directory configured in the HOSTS value of the
6256 @code{PEERINFO} configuration section to store PEERINFO information.
6257 For all files found in this directory valid HELLO messages are extracted.
6258 In addition it loads HELLO messages shipped with the GNUnet distribution.
6259 These HELLOs are used to simplify network bootstrapping by providing
6260 valid peer information with the distribution.
6261 The use of these HELLOs can be prevented by setting the
6262 @code{USE_INCLUDED_HELLOS} in the @code{PEERINFO} configuration section to
6263 @code{NO}. Files containing invalid information are removed.
6264
6265 @node Managing Information
6266 @subsection Managing Information
6267
6268
6269
6270 The PEERINFO services stores information about known PEERS and a single
6271 HELLO message for every peer.
6272 A peer does not need to have a HELLO if no information are available.
6273 HELLO information from different sources, for example a HELLO obtained
6274 from a remote HOSTLIST and a second HELLO stored on disk, are combined
6275 and merged into one single HELLO message per peer which will be given to
6276 clients. During this merge process the HELLO is immediately written to
6277 disk to ensure persistence.
6278
6279 PEERINFO in addition periodically scans the directory where information
6280 are stored for empty HELLO messages with expired TRANSPORT addresses.
6281 This periodic task scans all files in the directory and recreates the
6282 HELLO messages it finds.
6283 Expired TRANSPORT addresses are removed from the HELLO and if the
6284 HELLO does not contain any valid addresses, it is discarded and removed
6285 from the disk.
6286
6287 @node Obtaining Information
6288 @subsection Obtaining Information
6289
6290
6291
6292 When a client requests information from PEERINFO, PEERINFO performs a
6293 lookup for the respective peer or all peers if desired and transmits this
6294 information to the client.
6295 The client can specify if friend-only HELLOs have to be included or not
6296 and PEERINFO filters the respective HELLO messages before transmitting
6297 information.
6298
6299 To notify clients about changes to PEERINFO information, PEERINFO
6300 maintains a list of clients interested in this notifications.
6301 Such a notification occurs if a HELLO for a peer was updated (due to a
6302 merge for example) or a new peer was added.
6303
6304 @node The PEERINFO Client-Service Protocol
6305 @subsection The PEERINFO Client-Service Protocol
6306
6307
6308
6309 To connect and disconnect to and from the PEERINFO Service PEERINFO
6310 utilizes the util client/server infrastructure, so no special messages
6311 types are used here.
6312
6313 To add information for a peer, the plain HELLO message is transmitted to
6314 the service without any wrapping. All pieces of information required are
6315 stored within the HELLO message.
6316 The PEERINFO service provides a message handler accepting and processing
6317 these HELLO messages.
6318
6319 When obtaining PEERINFO information using the iterate functionality
6320 specific messages are used. To obtain information for all peers, a
6321 @code{struct ListAllPeersMessage} with message type
6322 @code{GNUNET_MESSAGE_TYPE_PEERINFO_GET_ALL} and a flag
6323 include_friend_only to indicate if friend-only HELLO messages should be
6324 included are transmitted. If information for a specific peer is required
6325 a @code{struct ListAllPeersMessage} with
6326 @code{GNUNET_MESSAGE_TYPE_PEERINFO_GET} containing the peer identity is
6327 used.
6328
6329 For both variants the PEERINFO service replies for each HELLO message it
6330 wants to transmit with a @code{struct ListAllPeersMessage} with type
6331 @code{GNUNET_MESSAGE_TYPE_PEERINFO_INFO} containing the plain HELLO.
6332 The final message is @code{struct GNUNET_MessageHeader} with type
6333 @code{GNUNET_MESSAGE_TYPE_PEERINFO_INFO}. If the client receives this
6334 message, it can proceed with the next request if any is pending.
6335
6336 @node libgnunetpeerinfo
6337 @subsection libgnunetpeerinfo
6338
6339
6340
6341 The PEERINFO API consists mainly of three different functionalities:
6342
6343 @itemize @bullet
6344 @item maintaining a connection to the service
6345 @item adding new information to the PEERINFO service
6346 @item retrieving information from the PEERINFO service
6347 @end itemize
6348
6349 @menu
6350 * Connecting to the PEERINFO Service::
6351 * Adding Information to the PEERINFO Service::
6352 * Obtaining Information from the PEERINFO Service::
6353 @end menu
6354
6355 @node Connecting to the PEERINFO Service
6356 @subsubsection Connecting to the PEERINFO Service
6357
6358
6359
6360 To connect to the PEERINFO service the function
6361 @code{GNUNET_PEERINFO_connect} is used, taking a configuration handle as
6362 an argument, and to disconnect from PEERINFO the function
6363 @code{GNUNET_PEERINFO_disconnect}, taking the PEERINFO
6364 handle returned from the connect function has to be called.
6365
6366 @node Adding Information to the PEERINFO Service
6367 @subsubsection Adding Information to the PEERINFO Service
6368
6369
6370
6371 @code{GNUNET_PEERINFO_add_peer} adds a new peer to the PEERINFO subsystem
6372 storage. This function takes the PEERINFO handle as an argument, the HELLO
6373 message to store and a continuation with a closure to be called with the
6374 result of the operation.
6375 The @code{GNUNET_PEERINFO_add_peer} returns a handle to this operation
6376 allowing to cancel the operation with the respective cancel function
6377 @code{GNUNET_PEERINFO_add_peer_cancel}. To retrieve information from
6378 PEERINFO you can iterate over all information stored with PEERINFO or you
6379 can tell PEERINFO to notify if new peer information are available.
6380
6381 @node Obtaining Information from the PEERINFO Service
6382 @subsubsection Obtaining Information from the PEERINFO Service
6383
6384
6385
6386 To iterate over information in PEERINFO you use
6387 @code{GNUNET_PEERINFO_iterate}.
6388 This function expects the PEERINFO handle, a flag if HELLO messages
6389 intended for friend only mode should be included, a timeout how long the
6390 operation should take and a callback with a callback closure to be called
6391 for the results.
6392 If you want to obtain information for a specific peer, you can specify
6393 the peer identity, if this identity is NULL, information for all peers are
6394 returned. The function returns a handle to allow to cancel the operation
6395 using @code{GNUNET_PEERINFO_iterate_cancel}.
6396
6397 To get notified when peer information changes, you can use
6398 @code{GNUNET_PEERINFO_notify}.
6399 This function expects a configuration handle and a flag if friend-only
6400 HELLO messages should be included. The PEERINFO service will notify you
6401 about every change and the callback function will be called to notify you
6402 about changes. The function returns a handle to cancel notifications
6403 with @code{GNUNET_PEERINFO_notify_cancel}.
6404
6405 @cindex PEERSTORE Subsystem
6406 @node PEERSTORE Subsystem
6407 @section PEERSTORE Subsystem
6408
6409
6410
6411 GNUnet's PEERSTORE subsystem offers persistent per-peer storage for other
6412 GNUnet subsystems. GNUnet subsystems can use PEERSTORE to persistently
6413 store and retrieve arbitrary data.
6414 Each data record stored with PEERSTORE contains the following fields:
6415
6416 @itemize @bullet
6417 @item subsystem: Name of the subsystem responsible for the record.
6418 @item peerid: Identity of the peer this record is related to.
6419 @item key: a key string identifying the record.
6420 @item value: binary record value.
6421 @item expiry: record expiry date.
6422 @end itemize
6423
6424 @menu
6425 * Functionality::
6426 * Architecture::
6427 * libgnunetpeerstore::
6428 @end menu
6429
6430 @node Functionality
6431 @subsection Functionality
6432
6433
6434
6435 Subsystems can store any type of value under a (subsystem, peerid, key)
6436 combination. A "replace" flag set during store operations forces the
6437 PEERSTORE to replace any old values stored under the same
6438 (subsystem, peerid, key) combination with the new value.
6439 Additionally, an expiry date is set after which the record is *possibly*
6440 deleted by PEERSTORE.
6441
6442 Subsystems can iterate over all values stored under any of the following
6443 combination of fields:
6444
6445 @itemize @bullet
6446 @item (subsystem)
6447 @item (subsystem, peerid)
6448 @item (subsystem, key)
6449 @item (subsystem, peerid, key)
6450 @end itemize
6451
6452 Subsystems can also request to be notified about any new values stored
6453 under a (subsystem, peerid, key) combination by sending a "watch"
6454 request to PEERSTORE.
6455
6456 @node Architecture
6457 @subsection Architecture
6458
6459
6460
6461 PEERSTORE implements the following components:
6462
6463 @itemize @bullet
6464 @item PEERSTORE service: Handles store, iterate and watch operations.
6465 @item PEERSTORE API: API to be used by other subsystems to communicate and
6466 issue commands to the PEERSTORE service.
6467 @item PEERSTORE plugins: Handles the persistent storage. At the moment,
6468 only an "sqlite" plugin is implemented.
6469 @end itemize
6470
6471 @cindex libgnunetpeerstore
6472 @node libgnunetpeerstore
6473 @subsection libgnunetpeerstore
6474
6475
6476
6477 libgnunetpeerstore is the library containing the PEERSTORE API. Subsystems
6478 wishing to communicate with the PEERSTORE service use this API to open a
6479 connection to PEERSTORE. This is done by calling
6480 @code{GNUNET_PEERSTORE_connect} which returns a handle to the newly
6481 created connection.
6482 This handle has to be used with any further calls to the API.
6483
6484 To store a new record, the function @code{GNUNET_PEERSTORE_store} is to
6485 be used which requires the record fields and a continuation function that
6486 will be called by the API after the STORE request is sent to the
6487 PEERSTORE service.
6488 Note that calling the continuation function does not mean that the record
6489 is successfully stored, only that the STORE request has been successfully
6490 sent to the PEERSTORE service.
6491 @code{GNUNET_PEERSTORE_store_cancel} can be called to cancel the STORE
6492 request only before the continuation function has been called.
6493
6494 To iterate over stored records, the function
6495 @code{GNUNET_PEERSTORE_iterate} is
6496 to be used. @emph{peerid} and @emph{key} can be set to NULL. An iterator
6497 callback function will be called with each matching record found and a
6498 NULL record at the end to signal the end of result set.
6499 @code{GNUNET_PEERSTORE_iterate_cancel} can be used to cancel the ITERATE
6500 request before the iterator callback is called with a NULL record.
6501
6502 To be notified with new values stored under a (subsystem, peerid, key)
6503 combination, the function @code{GNUNET_PEERSTORE_watch} is to be used.
6504 This will register the watcher with the PEERSTORE service, any new
6505 records matching the given combination will trigger the callback
6506 function passed to @code{GNUNET_PEERSTORE_watch}. This continues until
6507 @code{GNUNET_PEERSTORE_watch_cancel} is called or the connection to the
6508 service is destroyed.
6509
6510 After the connection is no longer needed, the function
6511 @code{GNUNET_PEERSTORE_disconnect} can be called to disconnect from the
6512 PEERSTORE service.
6513 Any pending ITERATE or WATCH requests will be destroyed.
6514 If the @code{sync_first} flag is set to @code{GNUNET_YES}, the API will
6515 delay the disconnection until all pending STORE requests are sent to
6516 the PEERSTORE service, otherwise, the pending STORE requests will be
6517 destroyed as well.
6518
6519 @cindex SET Subsystem
6520 @node SET Subsystem
6521 @section SET Subsystem
6522
6523
6524
6525 The SET service implements efficient set operations between two peers
6526 over a mesh tunnel.
6527 Currently, set union and set intersection are the only supported
6528 operations. Elements of a set consist of an @emph{element type} and
6529 arbitrary binary @emph{data}.
6530 The size of an element's data is limited to around 62 KB.
6531
6532 @menu
6533 * Local Sets::
6534 * Set Modifications::
6535 * Set Operations::
6536 * Result Elements::
6537 * libgnunetset::
6538 * The SET Client-Service Protocol::
6539 * The SET Intersection Peer-to-Peer Protocol::
6540 * The SET Union Peer-to-Peer Protocol::
6541 @end menu
6542
6543 @node Local Sets
6544 @subsection Local Sets
6545
6546
6547
6548 Sets created by a local client can be modified and reused for multiple
6549 operations. As each set operation requires potentially expensive special
6550 auxiliary data to be computed for each element of a set, a set can only
6551 participate in one type of set operation (i.e. union or intersection).
6552 The type of a set is determined upon its creation.
6553 If a the elements of a set are needed for an operation of a different
6554 type, all of the set's element must be copied to a new set of appropriate
6555 type.
6556
6557 @node Set Modifications
6558 @subsection Set Modifications
6559
6560
6561
6562 Even when set operations are active, one can add to and remove elements
6563 from a set.
6564 However, these changes will only be visible to operations that have been
6565 created after the changes have taken place. That is, every set operation
6566 only sees a snapshot of the set from the time the operation was started.
6567 This mechanism is @emph{not} implemented by copying the whole set, but by
6568 attaching @emph{generation information} to each element and operation.
6569
6570 @node Set Operations
6571 @subsection Set Operations
6572
6573
6574
6575 Set operations can be started in two ways: Either by accepting an
6576 operation request from a remote peer, or by requesting a set operation
6577 from a remote peer.
6578 Set operations are uniquely identified by the involved @emph{peers}, an
6579 @emph{application id} and the @emph{operation type}.
6580
6581 The client is notified of incoming set operations by @emph{set listeners}.
6582 A set listener listens for incoming operations of a specific operation
6583 type and application id.
6584 Once notified of an incoming set request, the client can accept the set
6585 request (providing a local set for the operation) or reject it.
6586
6587 @node Result Elements
6588 @subsection Result Elements
6589
6590
6591
6592 The SET service has three @emph{result modes} that determine how an
6593 operation's result set is delivered to the client:
6594
6595 @itemize @bullet
6596 @item @strong{Full Result Set.} All elements of set resulting from the set
6597 operation are returned to the client.
6598 @item @strong{Added Elements.} Only elements that result from the
6599 operation and are not already in the local peer's set are returned.
6600 Note that for some operations (like set intersection) this result mode
6601 will never return any elements.
6602 This can be useful if only the remove peer is actually interested in
6603 the result of the set operation.
6604 @item @strong{Removed Elements.} Only elements that are in the local
6605 peer's initial set but not in the operation's result set are returned.
6606 Note that for some operations (like set union) this result mode will
6607 never return any elements. This can be useful if only the remove peer is
6608 actually interested in the result of the set operation.
6609 @end itemize
6610
6611 @cindex libgnunetset
6612 @node libgnunetset
6613 @subsection libgnunetset
6614
6615
6616
6617 @menu
6618 * Sets::
6619 * Listeners::
6620 * Operations::
6621 * Supplying a Set::
6622 * The Result Callback::
6623 @end menu
6624
6625 @node Sets
6626 @subsubsection Sets
6627
6628
6629
6630 New sets are created with @code{GNUNET_SET_create}. Both the local peer's
6631 configuration (as each set has its own client connection) and the
6632 operation type must be specified.
6633 The set exists until either the client calls @code{GNUNET_SET_destroy} or
6634 the client's connection to the service is disrupted.
6635 In the latter case, the client is notified by the return value of
6636 functions dealing with sets. This return value must always be checked.
6637
6638 Elements are added and removed with @code{GNUNET_SET_add_element} and
6639 @code{GNUNET_SET_remove_element}.
6640
6641 @node Listeners
6642 @subsubsection Listeners
6643
6644
6645
6646 Listeners are created with @code{GNUNET_SET_listen}. Each time time a
6647 remote peer suggests a set operation with an application id and operation
6648 type matching a listener, the listener's callback is invoked.
6649 The client then must synchronously call either @code{GNUNET_SET_accept}
6650 or @code{GNUNET_SET_reject}. Note that the operation will not be started
6651 until the client calls @code{GNUNET_SET_commit}
6652 (see Section "Supplying a Set").
6653
6654 @node Operations
6655 @subsubsection Operations
6656
6657
6658
6659 Operations to be initiated by the local peer are created with
6660 @code{GNUNET_SET_prepare}. Note that the operation will not be started
6661 until the client calls @code{GNUNET_SET_commit}
6662 (see Section "Supplying a Set").
6663
6664 @node Supplying a Set
6665 @subsubsection Supplying a Set
6666
6667
6668
6669 To create symmetry between the two ways of starting a set operation
6670 (accepting and initiating it), the operation handles returned by
6671 @code{GNUNET_SET_accept} and @code{GNUNET_SET_prepare} do not yet have a
6672 set to operate on, thus they can not do any work yet.
6673
6674 The client must call @code{GNUNET_SET_commit} to specify a set to use for
6675 an operation. @code{GNUNET_SET_commit} may only be called once per set
6676 operation.
6677
6678 @node The Result Callback
6679 @subsubsection The Result Callback
6680
6681
6682
6683 Clients must specify both a result mode and a result callback with
6684 @code{GNUNET_SET_accept} and @code{GNUNET_SET_prepare}. The result
6685 callback with a status indicating either that an element was received, or
6686 the operation failed or succeeded.
6687 The interpretation of the received element depends on the result mode.
6688 The callback needs to know which result mode it is used in, as the
6689 arguments do not indicate if an element is part of the full result set,
6690 or if it is in the difference between the original set and the final set.
6691
6692 @node The SET Client-Service Protocol
6693 @subsection The SET Client-Service Protocol
6694
6695
6696
6697 @menu
6698 * Creating Sets::
6699 * Listeners2::
6700 * Initiating Operations::
6701 * Modifying Sets::
6702 * Results and Operation Status::
6703 * Iterating Sets::
6704 @end menu
6705
6706 @node Creating Sets
6707 @subsubsection Creating Sets
6708
6709
6710
6711 For each set of a client, there exists a client connection to the service.
6712 Sets are created by sending the @code{GNUNET_SERVICE_SET_CREATE} message
6713 over a new client connection. Multiple operations for one set are
6714 multiplexed over one client connection, using a request id supplied by
6715 the client.
6716
6717 @node Listeners2
6718 @subsubsection Listeners2
6719
6720
6721
6722 Each listener also requires a seperate client connection. By sending the
6723 @code{GNUNET_SERVICE_SET_LISTEN} message, the client notifies the service
6724 of the application id and operation type it is interested in. A client
6725 rejects an incoming request by sending @code{GNUNET_SERVICE_SET_REJECT}
6726 on the listener's client connection.
6727 In contrast, when accepting an incoming request, a
6728 @code{GNUNET_SERVICE_SET_ACCEPT} message must be sent over the@ set that
6729 is supplied for the set operation.
6730
6731 @node Initiating Operations
6732 @subsubsection Initiating Operations
6733
6734
6735
6736 Operations with remote peers are initiated by sending a
6737 @code{GNUNET_SERVICE_SET_EVALUATE} message to the service. The@ client
6738 connection that this message is sent by determines the set to use.
6739
6740 @node Modifying Sets
6741 @subsubsection Modifying Sets
6742
6743
6744
6745 Sets are modified with the @code{GNUNET_SERVICE_SET_ADD} and
6746 @code{GNUNET_SERVICE_SET_REMOVE} messages.
6747
6748
6749 @c %@menu
6750 @c %* Results and Operation Status::
6751 @c %* Iterating Sets::
6752 @c %@end menu
6753
6754 @node Results and Operation Status
6755 @subsubsection Results and Operation Status
6756
6757
6758 The service notifies the client of result elements and success/failure of
6759 a set operation with the @code{GNUNET_SERVICE_SET_RESULT} message.
6760
6761 @node Iterating Sets
6762 @subsubsection Iterating Sets
6763
6764
6765
6766 All elements of a set can be requested by sending
6767 @code{GNUNET_SERVICE_SET_ITER_REQUEST}. The server responds with
6768 @code{GNUNET_SERVICE_SET_ITER_ELEMENT} and eventually terminates the
6769 iteration with @code{GNUNET_SERVICE_SET_ITER_DONE}.
6770 After each received element, the client
6771 must send @code{GNUNET_SERVICE_SET_ITER_ACK}. Note that only one set
6772 iteration may be active for a set at any given time.
6773
6774 @node The SET Intersection Peer-to-Peer Protocol
6775 @subsection The SET Intersection Peer-to-Peer Protocol
6776
6777
6778
6779 The intersection protocol operates over CADET and starts with a
6780 GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST being sent by the peer
6781 initiating the operation to the peer listening for inbound requests.
6782 It includes the number of elements of the initiating peer, which is used
6783 to decide which side will send a Bloom filter first.
6784
6785 The listening peer checks if the operation type and application
6786 identifier are acceptable for its current state.
6787 If not, it responds with a GNUNET_MESSAGE_TYPE_SET_RESULT and a status of
6788 GNUNET_SET_STATUS_FAILURE (and terminates the CADET channel).
6789
6790 If the application accepts the request, the listener sends back a
6791 @code{GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_ELEMENT_INFO} if it has
6792 more elements in the set than the client.
6793 Otherwise, it immediately starts with the Bloom filter exchange.
6794 If the initiator receives a
6795 @code{GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_ELEMENT_INFO} response,
6796 it beings the Bloom filter exchange, unless the set size is indicated to
6797 be zero, in which case the intersection is considered finished after
6798 just the initial handshake.
6799
6800
6801 @menu
6802 * The Bloom filter exchange::
6803 * Salt::
6804 @end menu
6805
6806 @node The Bloom filter exchange
6807 @subsubsection The Bloom filter exchange
6808
6809
6810
6811 In this phase, each peer transmits a Bloom filter over the remaining
6812 keys of the local set to the other peer using a
6813 @code{GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_BF} message. This
6814 message additionally includes the number of elements left in the sender's
6815 set, as well as the XOR over all of the keys in that set.
6816
6817 The number of bits 'k' set per element in the Bloom filter is calculated
6818 based on the relative size of the two sets.
6819 Furthermore, the size of the Bloom filter is calculated based on 'k' and
6820 the number of elements in the set to maximize the amount of data filtered
6821 per byte transmitted on the wire (while avoiding an excessively high
6822 number of iterations).
6823
6824 The receiver of the message removes all elements from its local set that
6825 do not pass the Bloom filter test.
6826 It then checks if the set size of the sender and the XOR over the keys
6827 match what is left of its own set. If they do, it sends a
6828 @code{GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_DONE} back to indicate
6829 that the latest set is the final result.
6830 Otherwise, the receiver starts another Bloom filter exchange, except
6831 this time as the sender.
6832
6833 @node Salt
6834 @subsubsection Salt
6835
6836
6837
6838 Bloomfilter operations are probabilistic: With some non-zero probability
6839 the test may incorrectly say an element is in the set, even though it is
6840 not.
6841
6842 To mitigate this problem, the intersection protocol iterates exchanging
6843 Bloom filters using a different random 32-bit salt in each iteration (the
6844 salt is also included in the message).
6845 With different salts, set operations may fail for different elements.
6846 Merging the results from the executions, the probability of failure drops
6847 to zero.
6848
6849 The iterations terminate once both peers have established that they have
6850 sets of the same size, and where the XOR over all keys computes the same
6851 512-bit value (leaving a failure probability of 2-511).
6852
6853 @node The SET Union Peer-to-Peer Protocol
6854 @subsection The SET Union Peer-to-Peer Protocol
6855
6856
6857
6858 The SET union protocol is based on Eppstein's efficient set reconciliation
6859 without prior context. You should read this paper first if you want to
6860 understand the protocol.
6861
6862 The union protocol operates over CADET and starts with a
6863 GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST being sent by the peer
6864 initiating the operation to the peer listening for inbound requests.
6865 It includes the number of elements of the initiating peer, which is
6866 currently not used.
6867
6868 The listening peer checks if the operation type and application
6869 identifier are acceptable for its current state. If not, it responds with
6870 a @code{GNUNET_MESSAGE_TYPE_SET_RESULT} and a status of
6871 @code{GNUNET_SET_STATUS_FAILURE} (and terminates the CADET channel).
6872
6873 If the application accepts the request, it sends back a strata estimator
6874 using a message of type GNUNET_MESSAGE_TYPE_SET_UNION_P2P_SE. The
6875 initiator evaluates the strata estimator and initiates the exchange of
6876 invertible Bloom filters, sending a GNUNET_MESSAGE_TYPE_SET_UNION_P2P_IBF.
6877
6878 During the IBF exchange, if the receiver cannot invert the Bloom filter or
6879 detects a cycle, it sends a larger IBF in response (up to a defined
6880 maximum limit; if that limit is reached, the operation fails).
6881 Elements decoded while processing the IBF are transmitted to the other
6882 peer using GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENTS, or requested from the
6883 other peer using GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENT_REQUESTS messages,
6884 depending on the sign observed during decoding of the IBF.
6885 Peers respond to a GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENT_REQUESTS message
6886 with the respective element in a GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENTS
6887 message. If the IBF fully decodes, the peer responds with a
6888 GNUNET_MESSAGE_TYPE_SET_UNION_P2P_DONE message instead of another
6889 GNUNET_MESSAGE_TYPE_SET_UNION_P2P_IBF.
6890
6891 All Bloom filter operations use a salt to mingle keys before hashing them
6892 into buckets, such that future iterations have a fresh chance of
6893 succeeding if they failed due to collisions before.
6894
6895 @cindex STATISTICS Subsystem
6896 @node STATISTICS Subsystem
6897 @section STATISTICS Subsystem
6898
6899
6900
6901 In GNUnet, the STATISTICS subsystem offers a central place for all
6902 subsystems to publish unsigned 64-bit integer run-time statistics.
6903 Keeping this information centrally means that there is a unified way for
6904 the user to obtain data on all subsystems, and individual subsystems do
6905 not have to always include a custom data export method for performance
6906 metrics and other statistics. For example, the TRANSPORT system uses
6907 STATISTICS to update information about the number of directly connected
6908 peers and the bandwidth that has been consumed by the various plugins.
6909 This information is valuable for diagnosing connectivity and performance
6910 issues.
6911
6912 Following the GNUnet service architecture, the STATISTICS subsystem is
6913 divided into an API which is exposed through the header
6914 @strong{gnunet_statistics_service.h} and the STATISTICS service
6915 @strong{gnunet-service-statistics}. The @strong{gnunet-statistics}
6916 command-line tool can be used to obtain (and change) information about
6917 the values stored by the STATISTICS service. The STATISTICS service does
6918 not communicate with other peers.
6919
6920 Data is stored in the STATISTICS service in the form of tuples
6921 @strong{(subsystem, name, value, persistence)}. The subsystem determines
6922 to which other GNUnet's subsystem the data belongs. name is the name
6923 through which value is associated. It uniquely identifies the record
6924 from among other records belonging to the same subsystem.
6925 In some parts of the code, the pair @strong{(subsystem, name)} is called
6926 a @strong{statistic} as it identifies the values stored in the STATISTCS
6927 service.The persistence flag determines if the record has to be preserved
6928 across service restarts. A record is said to be persistent if this flag
6929 is set for it; if not, the record is treated as a non-persistent record
6930 and it is lost after service restart. Persistent records are written to
6931 and read from the file @strong{statistics.data} before shutdown
6932 and upon startup. The file is located in the HOME directory of the peer.
6933
6934 An anomaly of the STATISTICS service is that it does not terminate
6935 immediately upon receiving a shutdown signal if it has any clients
6936 connected to it. It waits for all the clients that are not monitors to
6937 close their connections before terminating itself.
6938 This is to prevent the loss of data during peer shutdown --- delaying the
6939 STATISTICS service shutdown helps other services to store important data
6940 to STATISTICS during shutdown.
6941
6942 @menu
6943 * libgnunetstatistics::
6944 * The STATISTICS Client-Service Protocol::
6945 @end menu
6946
6947 @cindex libgnunetstatistics
6948 @node libgnunetstatistics
6949 @subsection libgnunetstatistics
6950
6951
6952
6953 @strong{libgnunetstatistics} is the library containing the API for the
6954 STATISTICS subsystem. Any process requiring to use STATISTICS should use
6955 this API by to open a connection to the STATISTICS service.
6956 This is done by calling the function @code{GNUNET_STATISTICS_create()}.
6957 This function takes the subsystem's name which is trying to use STATISTICS
6958 and a configuration.
6959 All values written to STATISTICS with this connection will be placed in
6960 the section corresponding to the given subsystem's name.
6961 The connection to STATISTICS can be destroyed with the function
6962 @code{GNUNET_STATISTICS_destroy()}. This function allows for the
6963 connection to be destroyed immediately or upon transferring all
6964 pending write requests to the service.
6965
6966 Note: STATISTICS subsystem can be disabled by setting @code{DISABLE = YES}
6967 under the @code{[STATISTICS]} section in the configuration. With such a
6968 configuration all calls to @code{GNUNET_STATISTICS_create()} return
6969 @code{NULL} as the STATISTICS subsystem is unavailable and no other
6970 functions from the API can be used.
6971
6972
6973 @menu
6974 * Statistics retrieval::
6975 * Setting statistics and updating them::
6976 * Watches::
6977 @end menu
6978
6979 @node Statistics retrieval
6980 @subsubsection Statistics retrieval
6981
6982
6983
6984 Once a connection to the statistics service is obtained, information
6985 about any other system which uses statistics can be retrieved with the
6986 function GNUNET_STATISTICS_get().
6987 This function takes the connection handle, the name of the subsystem
6988 whose information we are interested in (a @code{NULL} value will
6989 retrieve information of all available subsystems using STATISTICS), the
6990 name of the statistic we are interested in (a @code{NULL} value will
6991 retrieve all available statistics), a continuation callback which is
6992 called when all of requested information is retrieved, an iterator
6993 callback which is called for each parameter in the retrieved information
6994 and a closure for the aforementioned callbacks. The library then invokes
6995 the iterator callback for each value matching the request.
6996
6997 Call to @code{GNUNET_STATISTICS_get()} is asynchronous and can be
6998 canceled with the function @code{GNUNET_STATISTICS_get_cancel()}.
6999 This is helpful when retrieving statistics takes too long and especially
7000 when we want to shutdown and cleanup everything.
7001
7002 @node Setting statistics and updating them
7003 @subsubsection Setting statistics and updating them
7004
7005
7006
7007 So far we have seen how to retrieve statistics, here we will learn how we
7008 can set statistics and update them so that other subsystems can retrieve
7009 them.
7010
7011 A new statistic can be set using the function
7012 @code{GNUNET_STATISTICS_set()}.
7013 This function takes the name of the statistic and its value and a flag to
7014 make the statistic persistent.
7015 The value of the statistic should be of the type @code{uint64_t}.
7016 The function does not take the name of the subsystem; it is determined
7017 from the previous @code{GNUNET_STATISTICS_create()} invocation. If
7018 the given statistic is already present, its value is overwritten.
7019
7020 An existing statistics can be updated, i.e its value can be increased or
7021 decreased by an amount with the function
7022 @code{GNUNET_STATISTICS_update()}.
7023 The parameters to this function are similar to
7024 @code{GNUNET_STATISTICS_set()}, except that it takes the amount to be
7025 changed as a type @code{int64_t} instead of the value.
7026
7027 The library will combine multiple set or update operations into one
7028 message if the client performs requests at a rate that is faster than the
7029 available IPC with the STATISTICS service. Thus, the client does not have
7030 to worry about sending requests too quickly.
7031
7032 @node Watches
7033 @subsubsection Watches
7034
7035
7036
7037 As interesting feature of STATISTICS lies in serving notifications
7038 whenever a statistic of our interest is modified.
7039 This is achieved by registering a watch through the function
7040 @code{GNUNET_STATISTICS_watch()}.
7041 The parameters of this function are similar to those of
7042 @code{GNUNET_STATISTICS_get()}.
7043 Changes to the respective statistic's value will then cause the given
7044 iterator callback to be called.
7045 Note: A watch can only be registered for a specific statistic. Hence
7046 the subsystem name and the parameter name cannot be @code{NULL} in a
7047 call to @code{GNUNET_STATISTICS_watch()}.
7048
7049 A registered watch will keep notifying any value changes until
7050 @code{GNUNET_STATISTICS_watch_cancel()} is called with the same
7051 parameters that are used for registering the watch.
7052
7053 @node The STATISTICS Client-Service Protocol
7054 @subsection The STATISTICS Client-Service Protocol
7055
7056
7057
7058 @menu
7059 * Statistics retrieval2::
7060 * Setting and updating statistics::
7061 * Watching for updates::
7062 @end menu
7063
7064 @node Statistics retrieval2
7065 @subsubsection Statistics retrieval2
7066
7067
7068
7069 To retrieve statistics, the client transmits a message of type
7070 @code{GNUNET_MESSAGE_TYPE_STATISTICS_GET} containing the given subsystem
7071 name and statistic parameter to the STATISTICS service.
7072 The service responds with a message of type
7073 @code{GNUNET_MESSAGE_TYPE_STATISTICS_VALUE} for each of the statistics
7074 parameters that match the client request for the client. The end of
7075 information retrieved is signaled by the service by sending a message of
7076 type @code{GNUNET_MESSAGE_TYPE_STATISTICS_END}.
7077
7078 @node Setting and updating statistics
7079 @subsubsection Setting and updating statistics
7080
7081
7082
7083 The subsystem name, parameter name, its value and the persistence flag are
7084 communicated to the service through the message
7085 @code{GNUNET_MESSAGE_TYPE_STATISTICS_SET}.
7086
7087 When the service receives a message of type
7088 @code{GNUNET_MESSAGE_TYPE_STATISTICS_SET}, it retrieves the subsystem
7089 name and checks for a statistic parameter with matching the name given in
7090 the message.
7091 If a statistic parameter is found, the value is overwritten by the new
7092 value from the message; if not found then a new statistic parameter is
7093 created with the given name and value.
7094
7095 In addition to just setting an absolute value, it is possible to perform a
7096 relative update by sending a message of type
7097 @code{GNUNET_MESSAGE_TYPE_STATISTICS_SET} with an update flag
7098 (@code{GNUNET_STATISTICS_SETFLAG_RELATIVE}) signifying that the value in
7099 the message should be treated as an update value.
7100
7101 @node Watching for updates
7102 @subsubsection Watching for updates
7103
7104
7105
7106 The function registers the watch at the service by sending a message of
7107 type @code{GNUNET_MESSAGE_TYPE_STATISTICS_WATCH}. The service then sends
7108 notifications through messages of type
7109 @code{GNUNET_MESSAGE_TYPE_STATISTICS_WATCH_VALUE} whenever the statistic
7110 parameter's value is changed.
7111
7112 @cindex DHT
7113 @cindex Distributed Hash Table
7114 @node Distributed Hash Table (DHT)
7115 @section Distributed Hash Table (DHT)
7116
7117
7118
7119 GNUnet includes a generic distributed hash table that can be used by
7120 developers building P2P applications in the framework.
7121 This section documents high-level features and how developers are
7122 expected to use the DHT.
7123 We have a research paper detailing how the DHT works.
7124 Also, Nate's thesis includes a detailed description and performance
7125 analysis (in chapter 6).
7126
7127 Key features of GNUnet's DHT include:
7128
7129 @itemize @bullet
7130 @item stores key-value pairs with values up to (approximately) 63k in size
7131 @item works with many underlay network topologies (small-world, random
7132 graph), underlay does not need to be a full mesh / clique
7133 @item support for extended queries (more than just a simple 'key'),
7134 filtering duplicate replies within the network (bloomfilter) and content
7135 validation (for details, please read the subsection on the block library)
7136 @item can (optionally) return paths taken by the PUT and GET operations
7137 to the application
7138 @item provides content replication to handle churn
7139 @end itemize
7140
7141 GNUnet's DHT is randomized and unreliable. Unreliable means that there is
7142 no strict guarantee that a value stored in the DHT is always
7143 found --- values are only found with high probability.
7144 While this is somewhat true in all P2P DHTs, GNUnet developers should be
7145 particularly wary of this fact (this will help you write secure,
7146 fault-tolerant code). Thus, when writing any application using the DHT,
7147 you should always consider the possibility that a value stored in the
7148 DHT by you or some other peer might simply not be returned, or returned
7149 with a significant delay.
7150 Your application logic must be written to tolerate this (naturally, some
7151 loss of performance or quality of service is expected in this case).
7152
7153 @menu
7154 * Block library and plugins::
7155 * libgnunetdht::
7156 * The DHT Client-Service Protocol::
7157 * The DHT Peer-to-Peer Protocol::
7158 @end menu
7159
7160 @node Block library and plugins
7161 @subsection Block library and plugins
7162
7163
7164
7165 @menu
7166 * What is a Block?::
7167 * The API of libgnunetblock::
7168 * Queries::
7169 * Sample Code::
7170 * Conclusion2::
7171 @end menu
7172
7173 @node What is a Block?
7174 @subsubsection What is a Block?
7175
7176
7177
7178 Blocks are small (< 63k) pieces of data stored under a key (struct
7179 GNUNET_HashCode). Blocks have a type (enum GNUNET_BlockType) which defines
7180 their data format. Blocks are used in GNUnet as units of static data
7181 exchanged between peers and stored (or cached) locally.
7182 Uses of blocks include file-sharing (the files are broken up into blocks),
7183 the VPN (DNS information is stored in blocks) and the DHT (all
7184 information in the DHT and meta-information for the maintenance of the
7185 DHT are both stored using blocks).
7186 The block subsystem provides a few common functions that must be
7187 available for any type of block.
7188
7189 @cindex libgnunetblock API
7190 @node The API of libgnunetblock
7191 @subsubsection The API of libgnunetblock
7192
7193
7194
7195 The block library requires for each (family of) block type(s) a block
7196 plugin (implementing @file{gnunet_block_plugin.h}) that provides basic
7197 functions that are needed by the DHT (and possibly other subsystems) to
7198 manage the block.
7199 These block plugins are typically implemented within their respective
7200 subsystems.
7201 The main block library is then used to locate, load and query the
7202 appropriate block plugin.
7203 Which plugin is appropriate is determined by the block type (which is
7204 just a 32-bit integer). Block plugins contain code that specifies which
7205 block types are supported by a given plugin. The block library loads all
7206 block plugins that are installed at the local peer and forwards the
7207 application request to the respective plugin.
7208
7209 The central functions of the block APIs (plugin and main library) are to
7210 allow the mapping of blocks to their respective key (if possible) and the
7211 ability to check that a block is well-formed and matches a given
7212 request (again, if possible).
7213 This way, GNUnet can avoid storing invalid blocks, storing blocks under
7214 the wrong key and forwarding blocks in response to a query that they do
7215 not answer.
7216
7217 One key function of block plugins is that it allows GNUnet to detect
7218 duplicate replies (via the Bloom filter). All plugins MUST support
7219 detecting duplicate replies (by adding the current response to the
7220 Bloom filter and rejecting it if it is encountered again).
7221 If a plugin fails to do this, responses may loop in the network.
7222
7223 @node Queries
7224 @subsubsection Queries
7225
7226
7227 The query format for any block in GNUnet consists of four main components.
7228 First, the type of the desired block must be specified. Second, the query
7229 must contain a hash code. The hash code is used for lookups in hash
7230 tables and databases and must not be unique for the block (however, if
7231 possible a unique hash should be used as this would be best for
7232 performance).
7233 Third, an optional Bloom filter can be specified to exclude known results;
7234 replies that hash to the bits set in the Bloom filter are considered
7235 invalid. False-positives can be eliminated by sending the same query
7236 again with a different Bloom filter mutator value, which parameterizes
7237 the hash function that is used.
7238 Finally, an optional application-specific "eXtended query" (xquery) can
7239 be specified to further constrain the results. It is entirely up to
7240 the type-specific plugin to determine whether or not a given block
7241 matches a query (type, hash, Bloom filter, and xquery).
7242 Naturally, not all xquery's are valid and some types of blocks may not
7243 support Bloom filters either, so the plugin also needs to check if the
7244 query is valid in the first place.
7245
7246 Depending on the results from the plugin, the DHT will then discard the
7247 (invalid) query, forward the query, discard the (invalid) reply, cache the
7248 (valid) reply, and/or forward the (valid and non-duplicate) reply.
7249
7250 @node Sample Code
7251 @subsubsection Sample Code
7252
7253
7254
7255 The source code in @strong{plugin_block_test.c} is a good starting point
7256 for new block plugins --- it does the minimal work by implementing a
7257 plugin that performs no validation at all.
7258 The respective @strong{Makefile.am} shows how to build and install a
7259 block plugin.
7260
7261 @node Conclusion2
7262 @subsubsection Conclusion2
7263
7264
7265
7266 In conclusion, GNUnet subsystems that want to use the DHT need to define a
7267 block format and write a plugin to match queries and replies. For testing,
7268 the @code{GNUNET_BLOCK_TYPE_TEST} block type can be used; it accepts
7269 any query as valid and any reply as matching any query.
7270 This type is also used for the DHT command line tools.
7271 However, it should NOT be used for normal applications due to the lack
7272 of error checking that results from this primitive implementation.
7273
7274 @cindex libgnunetdht
7275 @node libgnunetdht
7276 @subsection libgnunetdht
7277
7278
7279
7280 The DHT API itself is pretty simple and offers the usual GET and PUT
7281 functions that work as expected. The specified block type refers to the
7282 block library which allows the DHT to run application-specific logic for
7283 data stored in the network.
7284
7285
7286 @menu
7287 * GET::
7288 * PUT::
7289 * MONITOR::
7290 * DHT Routing Options::
7291 @end menu
7292
7293 @node GET
7294 @subsubsection GET
7295
7296
7297
7298 When using GET, the main consideration for developers (other than the
7299 block library) should be that after issuing a GET, the DHT will
7300 continuously cause (small amounts of) network traffic until the operation
7301 is explicitly canceled.
7302 So GET does not simply send out a single network request once; instead,
7303 the DHT will continue to search for data. This is needed to achieve good
7304 success rates and also handles the case where the respective PUT
7305 operation happens after the GET operation was started.
7306 Developers should not cancel an existing GET operation and then
7307 explicitly re-start it to trigger a new round of network requests;
7308 this is simply inefficient, especially as the internal automated version
7309 can be more efficient, for example by filtering results in the network
7310 that have already been returned.
7311
7312 If an application that performs a GET request has a set of replies that it
7313 already knows and would like to filter, it can call@
7314 @code{GNUNET_DHT_get_filter_known_results} with an array of hashes over
7315 the respective blocks to tell the DHT that these results are not
7316 desired (any more).
7317 This way, the DHT will filter the respective blocks using the block
7318 library in the network, which may result in a significant reduction in
7319 bandwidth consumption.
7320
7321 @node PUT
7322 @subsubsection PUT
7323
7324
7325
7326 @c inconsistent use of ``must'' above it's written ``MUST''
7327 In contrast to GET operations, developers @strong{must} manually re-run
7328 PUT operations periodically (if they intend the content to continue to be
7329 available). Content stored in the DHT expires or might be lost due to
7330 churn.
7331 Furthermore, GNUnet's DHT typically requires multiple rounds of PUT
7332 operations before a key-value pair is consistently available to all
7333 peers (the DHT randomizes paths and thus storage locations, and only
7334 after multiple rounds of PUTs there will be a sufficient number of
7335 replicas in large DHTs). An explicit PUT operation using the DHT API will
7336 only cause network traffic once, so in order to ensure basic availability
7337 and resistance to churn (and adversaries), PUTs must be repeated.
7338 While the exact frequency depends on the application, a rule of thumb is
7339 that there should be at least a dozen PUT operations within the content
7340 lifetime. Content in the DHT typically expires after one day, so
7341 DHT PUT operations should be repeated at least every 1-2 hours.
7342
7343 @node MONITOR
7344 @subsubsection MONITOR
7345
7346
7347
7348 The DHT API also allows applications to monitor messages crossing the
7349 local DHT service.
7350 The types of messages used by the DHT are GET, PUT and RESULT messages.
7351 Using the monitoring API, applications can choose to monitor these
7352 requests, possibly limiting themselves to requests for a particular block
7353 type.
7354
7355 The monitoring API is not only useful for diagnostics, it can also be
7356 used to trigger application operations based on PUT operations.
7357 For example, an application may use PUTs to distribute work requests to
7358 other peers.
7359 The workers would then monitor for PUTs that give them work, instead of
7360 looking for work using GET operations.
7361 This can be beneficial, especially if the workers have no good way to
7362 guess the keys under which work would be stored.
7363 Naturally, additional protocols might be needed to ensure that the desired
7364 number of workers will process the distributed workload.
7365
7366 @node DHT Routing Options
7367 @subsubsection DHT Routing Options
7368
7369
7370
7371 There are two important options for GET and PUT requests:
7372
7373 @table @asis
7374 @item GNUNET_DHT_RO_DEMULITPLEX_EVERYWHERE This option means that all
7375 peers should process the request, even if their peer ID is not closest to
7376 the key. For a PUT request, this means that all peers that a request
7377 traverses may make a copy of the data.
7378 Similarly for a GET request, all peers will check their local database
7379 for a result. Setting this option can thus significantly improve caching
7380 and reduce bandwidth consumption --- at the expense of a larger DHT
7381 database. If in doubt, we recommend that this option should be used.
7382 @item GNUNET_DHT_RO_RECORD_ROUTE This option instructs the DHT to record
7383 the path that a GET or a PUT request is taking through the overlay
7384 network. The resulting paths are then returned to the application with
7385 the respective result. This allows the receiver of a result to construct
7386 a path to the originator of the data, which might then be used for
7387 routing. Naturally, setting this option requires additional bandwidth
7388 and disk space, so applications should only set this if the paths are
7389 needed by the application logic.
7390 @item GNUNET_DHT_RO_FIND_PEER This option is an internal option used by
7391 the DHT's peer discovery mechanism and should not be used by applications.
7392 @item GNUNET_DHT_RO_BART This option is currently not implemented. It may
7393 in the future offer performance improvements for clique topologies.
7394 @end table
7395
7396 @node The DHT Client-Service Protocol
7397 @subsection The DHT Client-Service Protocol
7398
7399
7400
7401 @menu
7402 * PUTting data into the DHT::
7403 * GETting data from the DHT::
7404 * Monitoring the DHT::
7405 @end menu
7406
7407 @node PUTting data into the DHT
7408 @subsubsection PUTting data into the DHT
7409
7410
7411
7412 To store (PUT) data into the DHT, the client sends a
7413 @code{struct GNUNET_DHT_ClientPutMessage} to the service.
7414 This message specifies the block type, routing options, the desired
7415 replication level, the expiration time, key,
7416 value and a 64-bit unique ID for the operation. The service responds with
7417 a @code{struct GNUNET_DHT_ClientPutConfirmationMessage} with the same
7418 64-bit unique ID. Note that the service sends the confirmation as soon as
7419 it has locally processed the PUT request. The PUT may still be
7420 propagating through the network at this time.
7421
7422 In the future, we may want to change this to provide (limited) feedback
7423 to the client, for example if we detect that the PUT operation had no
7424 effect because the same key-value pair was already stored in the DHT.
7425 However, changing this would also require additional state and messages
7426 in the P2P interaction.
7427
7428 @node GETting data from the DHT
7429 @subsubsection GETting data from the DHT
7430
7431
7432
7433 To retrieve (GET) data from the DHT, the client sends a
7434 @code{struct GNUNET_DHT_ClientGetMessage} to the service. The message
7435 specifies routing options, a replication level (for replicating the GET,
7436 not the content), the desired block type, the key, the (optional)
7437 extended query and unique 64-bit request ID.
7438
7439 Additionally, the client may send any number of
7440 @code{struct GNUNET_DHT_ClientGetResultSeenMessage}s to notify the
7441 service about results that the client is already aware of.
7442 These messages consist of the key, the unique 64-bit ID of the request,
7443 and an arbitrary number of hash codes over the blocks that the client is
7444 already aware of. As messages are restricted to 64k, a client that
7445 already knows more than about a thousand blocks may need to send
7446 several of these messages. Naturally, the client should transmit these
7447 messages as quickly as possible after the original GET request such that
7448 the DHT can filter those results in the network early on. Naturally, as
7449 these messages are sent after the original request, it is conceivable
7450 that the DHT service may return blocks that match those already known
7451 to the client anyway.
7452
7453 In response to a GET request, the service will send @code{struct
7454 GNUNET_DHT_ClientResultMessage}s to the client. These messages contain the
7455 block type, expiration, key, unique ID of the request and of course the
7456 value (a block). Depending on the options set for the respective
7457 operations, the replies may also contain the path the GET and/or the PUT
7458 took through the network.
7459
7460 A client can stop receiving replies either by disconnecting or by sending
7461 a @code{struct GNUNET_DHT_ClientGetStopMessage} which must contain the
7462 key and the 64-bit unique ID of the original request. Using an
7463 explicit "stop" message is more common as this allows a client to run
7464 many concurrent GET operations over the same connection with the DHT
7465 service --- and to stop them individually.
7466
7467 @node Monitoring the DHT
7468 @subsubsection Monitoring the DHT
7469
7470
7471
7472 To begin monitoring, the client sends a
7473 @code{struct GNUNET_DHT_MonitorStartStop} message to the DHT service.
7474 In this message, flags can be set to enable (or disable) monitoring of
7475 GET, PUT and RESULT messages that pass through a peer. The message can
7476 also restrict monitoring to a particular block type or a particular key.
7477 Once monitoring is enabled, the DHT service will notify the client about
7478 any matching event using @code{struct GNUNET_DHT_MonitorGetMessage}s for
7479 GET events, @code{struct GNUNET_DHT_MonitorPutMessage} for PUT events
7480 and @code{struct GNUNET_DHT_MonitorGetRespMessage} for RESULTs. Each of
7481 these messages contains all of the information about the event.
7482
7483 @node The DHT Peer-to-Peer Protocol
7484 @subsection The DHT Peer-to-Peer Protocol
7485
7486
7487
7488 @menu
7489 * Routing GETs or PUTs::
7490 * PUTting data into the DHT2::
7491 * GETting data from the DHT2::
7492 @end menu
7493
7494 @node Routing GETs or PUTs
7495 @subsubsection Routing GETs or PUTs
7496
7497
7498
7499 When routing GETs or PUTs, the DHT service selects a suitable subset of
7500 neighbours for forwarding. The exact number of neighbours can be zero or
7501 more and depends on the hop counter of the query (initially zero) in
7502 relation to the (log of) the network size estimate, the desired
7503 replication level and the peer's connectivity.
7504 Depending on the hop counter and our network size estimate, the selection
7505 of the peers maybe randomized or by proximity to the key.
7506 Furthermore, requests include a set of peers that a request has already
7507 traversed; those peers are also excluded from the selection.
7508
7509 @node PUTting data into the DHT2
7510 @subsubsection PUTting data into the DHT2
7511
7512
7513
7514 To PUT data into the DHT, the service sends a @code{struct PeerPutMessage}
7515 of type @code{GNUNET_MESSAGE_TYPE_DHT_P2P_PUT} to the respective
7516 neighbour.
7517 In addition to the usual information about the content (type, routing
7518 options, desired replication level for the content, expiration time, key
7519 and value), the message contains a fixed-size Bloom filter with
7520 information about which peers (may) have already seen this request.
7521 This Bloom filter is used to ensure that DHT messages never loop back to
7522 a peer that has already processed the request.
7523 Additionally, the message includes the current hop counter and, depending
7524 on the routing options, the message may include the full path that the
7525 message has taken so far.
7526 The Bloom filter should already contain the identity of the previous hop;
7527 however, the path should not include the identity of the previous hop and
7528 the receiver should append the identity of the sender to the path, not
7529 its own identity (this is done to reduce bandwidth).
7530
7531 @node GETting data from the DHT2
7532 @subsubsection GETting data from the DHT2
7533
7534
7535
7536 A peer can search the DHT by sending @code{struct PeerGetMessage}s of type
7537 @code{GNUNET_MESSAGE_TYPE_DHT_P2P_GET} to other peers. In addition to the
7538 usual information about the request (type, routing options, desired
7539 replication level for the request, the key and the extended query), a GET
7540 request also contains a hop counter, a Bloom filter over the peers
7541 that have processed the request already and depending on the routing
7542 options the full path traversed by the GET.
7543 Finally, a GET request includes a variable-size second Bloom filter and a
7544 so-called Bloom filter mutator value which together indicate which
7545 replies the sender has already seen. During the lookup, each block that
7546 matches they block type, key and extended query is additionally subjected
7547 to a test against this Bloom filter.
7548 The block plugin is expected to take the hash of the block and combine it
7549 with the mutator value and check if the result is not yet in the Bloom
7550 filter. The originator of the query will from time to time modify the
7551 mutator to (eventually) allow false-positives filtered by the Bloom filter
7552 to be returned.
7553
7554 Peers that receive a GET request perform a local lookup (depending on
7555 their proximity to the key and the query options) and forward the request
7556 to other peers.
7557 They then remember the request (including the Bloom filter for blocking
7558 duplicate results) and when they obtain a matching, non-filtered response
7559 a @code{struct PeerResultMessage} of type
7560 @code{GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT} is forwarded to the previous
7561 hop.
7562 Whenever a result is forwarded, the block plugin is used to update the
7563 Bloom filter accordingly, to ensure that the same result is never
7564 forwarded more than once.
7565 The DHT service may also cache forwarded results locally if the
7566 "CACHE_RESULTS" option is set to "YES" in the configuration.
7567
7568 @cindex GNS
7569 @cindex GNU Name System
7570 @node GNU Name System (GNS)
7571 @section GNU Name System (GNS)
7572
7573
7574
7575 The GNU Name System (GNS) is a decentralized database that enables users
7576 to securely resolve names to values.
7577 Names can be used to identify other users (for example, in social
7578 networking), or network services (for example, VPN services running at a
7579 peer in GNUnet, or purely IP-based services on the Internet).
7580 Users interact with GNS by typing in a hostname that ends in a
7581 top-level domain that is configured in the ``GNS'' section, matches
7582 an identity of the user or ends in a Base32-encoded public key.
7583
7584 Videos giving an overview of most of the GNS and the motivations behind
7585 it is available here and here.
7586 The remainder of this chapter targets developers that are familiar with
7587 high level concepts of GNS as presented in these talks.
7588 @c TODO: Add links to here and here and to these.
7589
7590 GNS-aware applications should use the GNS resolver to obtain the
7591 respective records that are stored under that name in GNS.
7592 Each record consists of a type, value, expiration time and flags.
7593
7594 The type specifies the format of the value. Types below 65536 correspond
7595 to DNS record types, larger values are used for GNS-specific records.
7596 Applications can define new GNS record types by reserving a number and
7597 implementing a plugin (which mostly needs to convert the binary value
7598 representation to a human-readable text format and vice-versa).
7599 The expiration time specifies how long the record is to be valid.
7600 The GNS API ensures that applications are only given non-expired values.
7601 The flags are typically irrelevant for applications, as GNS uses them
7602 internally to control visibility and validity of records.
7603
7604 Records are stored along with a signature.
7605 The signature is generated using the private key of the authoritative
7606 zone. This allows any GNS resolver to verify the correctness of a
7607 name-value mapping.
7608
7609 Internally, GNS uses the NAMECACHE to cache information obtained from
7610 other users, the NAMESTORE to store information specific to the local
7611 users, and the DHT to exchange data between users.
7612 A plugin API is used to enable applications to define new GNS
7613 record types.
7614
7615 @menu
7616 * libgnunetgns::
7617 * libgnunetgnsrecord::
7618 * GNS plugins::
7619 * The GNS Client-Service Protocol::
7620 * Hijacking the DNS-Traffic using gnunet-service-dns::
7621 * Serving DNS lookups via GNS on W32::
7622 * Importing DNS Zones into GNS::
7623 @end menu
7624
7625 @node libgnunetgns
7626 @subsection libgnunetgns
7627
7628
7629
7630 The GNS API itself is extremely simple. Clients first connect to the
7631 GNS service using @code{GNUNET_GNS_connect}.
7632 They can then perform lookups using @code{GNUNET_GNS_lookup} or cancel
7633 pending lookups using @code{GNUNET_GNS_lookup_cancel}.
7634 Once finished, clients disconnect using @code{GNUNET_GNS_disconnect}.
7635
7636 @menu
7637 * Looking up records::
7638 * Accessing the records::
7639 * Creating records::
7640 * Future work::
7641 @end menu
7642
7643 @node Looking up records
7644 @subsubsection Looking up records
7645
7646
7647
7648 @code{GNUNET_GNS_lookup} takes a number of arguments:
7649
7650 @table @asis
7651 @item handle This is simply the GNS connection handle from
7652 @code{GNUNET_GNS_connect}.
7653 @item name The client needs to specify the name to
7654 be resolved. This can be any valid DNS or GNS hostname.
7655 @item zone The client
7656 needs to specify the public key of the GNS zone against which the
7657 resolution should be done.
7658 Note that a key must be provided, the client should
7659 look up plausible values using its configuration,
7660 the identity service and by attempting to interpret the
7661 TLD as a base32-encoded public key.
7662 @item type This is the desired GNS or DNS record type
7663 to look for. While all records for the given name will be returned, this
7664 can be important if the client wants to resolve record types that
7665 themselves delegate resolution, such as CNAME, PKEY or GNS2DNS.
7666 Resolving a record of any of these types will only work if the respective
7667 record type is specified in the request, as the GNS resolver will
7668 otherwise follow the delegation and return the records from the
7669 respective destination, instead of the delegating record.
7670 @item only_cached This argument should typically be set to
7671 @code{GNUNET_NO}. Setting it to @code{GNUNET_YES} disables resolution via
7672 the overlay network.
7673 @item shorten_zone_key If GNS encounters new names during resolution,
7674 their respective zones can automatically be learned and added to the
7675 "shorten zone". If this is desired, clients must pass the private key of
7676 the shorten zone. If NULL is passed, shortening is disabled.
7677 @item proc This argument identifies
7678 the function to call with the result. It is given proc_cls, the number of
7679 records found (possibly zero) and the array of the records as arguments.
7680 proc will only be called once. After proc,> has been called, the lookup
7681 must no longer be canceled.
7682 @item proc_cls The closure for proc.
7683 @end table
7684
7685 @node Accessing the records
7686 @subsubsection Accessing the records
7687
7688
7689
7690 The @code{libgnunetgnsrecord} library provides an API to manipulate the
7691 GNS record array that is given to proc. In particular, it offers
7692 functions such as converting record values to human-readable
7693 strings (and back). However, most @code{libgnunetgnsrecord} functions are
7694 not interesting to GNS client applications.
7695
7696 For DNS records, the @code{libgnunetdnsparser} library provides
7697 functions for parsing (and serializing) common types of DNS records.
7698
7699 @node Creating records
7700 @subsubsection Creating records
7701
7702
7703
7704 Creating GNS records is typically done by building the respective record
7705 information (possibly with the help of @code{libgnunetgnsrecord} and
7706 @code{libgnunetdnsparser}) and then using the @code{libgnunetnamestore} to
7707 publish the information. The GNS API is not involved in this
7708 operation.
7709
7710 @node Future work
7711 @subsubsection Future work
7712
7713
7714
7715 In the future, we want to expand @code{libgnunetgns} to allow
7716 applications to observe shortening operations performed during GNS
7717 resolution, for example so that users can receive visual feedback when
7718 this happens.
7719
7720 @node libgnunetgnsrecord
7721 @subsection libgnunetgnsrecord
7722
7723
7724
7725 The @code{libgnunetgnsrecord} library is used to manipulate GNS
7726 records (in plaintext or in their encrypted format).
7727 Applications mostly interact with @code{libgnunetgnsrecord} by using the
7728 functions to convert GNS record values to strings or vice-versa, or to
7729 lookup a GNS record type number by name (or vice-versa).
7730 The library also provides various other functions that are mostly
7731 used internally within GNS, such as converting keys to names, checking for
7732 expiration, encrypting GNS records to GNS blocks, verifying GNS block
7733 signatures and decrypting GNS records from GNS blocks.
7734
7735 We will now discuss the four commonly used functions of the API.@
7736 @code{libgnunetgnsrecord} does not perform these operations itself,
7737 but instead uses plugins to perform the operation.
7738 GNUnet includes plugins to support common DNS record types as well as
7739 standard GNS record types.
7740
7741 @menu
7742 * Value handling::
7743 * Type handling::
7744 @end menu
7745
7746 @node Value handling
7747 @subsubsection Value handling
7748
7749
7750
7751 @code{GNUNET_GNSRECORD_value_to_string} can be used to convert
7752 the (binary) representation of a GNS record value to a human readable,
7753 0-terminated UTF-8 string.
7754 NULL is returned if the specified record type is not supported by any
7755 available plugin.
7756
7757 @code{GNUNET_GNSRECORD_string_to_value} can be used to try to convert a
7758 human readable string to the respective (binary) representation of
7759 a GNS record value.
7760
7761 @node Type handling
7762 @subsubsection Type handling
7763
7764
7765
7766 @code{GNUNET_GNSRECORD_typename_to_number} can be used to obtain the
7767 numeric value associated with a given typename. For example, given the
7768 typename "A" (for DNS A reocrds), the function will return the number 1.
7769 A list of common DNS record types is
7770 @uref{http://en.wikipedia.org/wiki/List_of_DNS_record_types, here}.
7771 Note that not all DNS record types are supported by GNUnet GNSRECORD
7772 plugins at this time.
7773
7774 @code{GNUNET_GNSRECORD_number_to_typename} can be used to obtain the
7775 typename associated with a given numeric value.
7776 For example, given the type number 1, the function will return the
7777 typename "A".
7778
7779 @node GNS plugins
7780 @subsection GNS plugins
7781
7782
7783
7784 Adding a new GNS record type typically involves writing (or extending) a
7785 GNSRECORD plugin. The plugin needs to implement the
7786 @code{gnunet_gnsrecord_plugin.h} API which provides basic functions that
7787 are needed by GNSRECORD to convert typenames and values of the respective
7788 record type to strings (and back).
7789 These gnsrecord plugins are typically implemented within their respective
7790 subsystems.
7791 Examples for such plugins can be found in the GNSRECORD, GNS and
7792 CONVERSATION subsystems.
7793
7794 The @code{libgnunetgnsrecord} library is then used to locate, load and
7795 query the appropriate gnsrecord plugin.
7796 Which plugin is appropriate is determined by the record type (which is
7797 just a 32-bit integer). The @code{libgnunetgnsrecord} library loads all
7798 block plugins that are installed at the local peer and forwards the
7799 application request to the plugins. If the record type is not
7800 supported by the plugin, it should simply return an error code.
7801
7802 The central functions of the block APIs (plugin and main library) are the
7803 same four functions for converting between values and strings, and
7804 typenames and numbers documented in the previous subsection.
7805
7806 @node The GNS Client-Service Protocol
7807 @subsection The GNS Client-Service Protocol
7808
7809
7810 The GNS client-service protocol consists of two simple messages, the
7811 @code{LOOKUP} message and the @code{LOOKUP_RESULT}. Each @code{LOOKUP}
7812 message contains a unique 32-bit identifier, which will be included in the
7813 corresponding response. Thus, clients can send many lookup requests in
7814 parallel and receive responses out-of-order.
7815 A @code{LOOKUP} request also includes the public key of the GNS zone,
7816 the desired record type and fields specifying whether shortening is
7817 enabled or networking is disabled. Finally, the @code{LOOKUP} message
7818 includes the name to be resolved.
7819
7820 The response includes the number of records and the records themselves
7821 in the format created by @code{GNUNET_GNSRECORD_records_serialize}.
7822 They can thus be deserialized using
7823 @code{GNUNET_GNSRECORD_records_deserialize}.
7824
7825 @node Hijacking the DNS-Traffic using gnunet-service-dns
7826 @subsection Hijacking the DNS-Traffic using gnunet-service-dns
7827
7828
7829
7830 This section documents how the gnunet-service-dns (and the
7831 gnunet-helper-dns) intercepts DNS queries from the local system.
7832 This is merely one method for how we can obtain GNS queries.
7833 It is also possible to change @code{resolv.conf} to point to a machine
7834 running @code{gnunet-dns2gns} or to modify libc's name system switch
7835 (NSS) configuration to include a GNS resolution plugin.
7836 The method described in this chapter is more of a last-ditch catch-all
7837 approach.
7838
7839 @code{gnunet-service-dns} enables intercepting DNS traffic using policy
7840 based routing.
7841 We MARK every outgoing DNS-packet if it was not sent by our application.
7842 Using a second routing table in the Linux kernel these marked packets are
7843 then routed through our virtual network interface and can thus be
7844 captured unchanged.
7845
7846 Our application then reads the query and decides how to handle it.
7847 If the query can be addressed via GNS, it is passed to
7848 @code{gnunet-service-gns} and resolved internally using GNS.
7849 In the future, a reverse query for an address of the configured virtual
7850 network could be answered with records kept about previous forward
7851 queries.
7852 Queries that are not hijacked by some application using the DNS service
7853 will be sent to the original recipient.
7854 The answer to the query will always be sent back through the virtual
7855 interface with the original nameserver as source address.
7856
7857
7858 @menu
7859 * Network Setup Details::
7860 @end menu
7861
7862 @node Network Setup Details
7863 @subsubsection Network Setup Details
7864
7865
7866
7867 The DNS interceptor adds the following rules to the Linux kernel:
7868 @example
7869 iptables -t mangle -I OUTPUT 1 -p udp --sport $LOCALPORT --dport 53 \
7870 -j ACCEPT iptables -t mangle -I OUTPUT 2 -p udp --dport 53 -j MARK \
7871 --set-mark 3 ip rule add fwmark 3 table2 ip route add default via \
7872 $VIRTUALDNS table2
7873 @end example
7874
7875 @c FIXME: Rewrite to reflect display which is no longer content by line
7876 @c FIXME: due to the < 74 characters limit.
7877 Line 1 makes sure that all packets coming from a port our application
7878 opened beforehand (@code{$LOCALPORT}) will be routed normally.
7879 Line 2 marks every other packet to a DNS-Server with mark 3 (chosen
7880 arbitrarily). The third line adds a routing policy based on this mark
7881 3 via the routing table.
7882
7883 @node Serving DNS lookups via GNS on W32
7884 @subsection Serving DNS lookups via GNS on W32
7885
7886
7887
7888 This section documents how the libw32nsp (and
7889 gnunet-gns-helper-service-w32) do DNS resolutions of DNS queries on the
7890 local system. This only applies to GNUnet running on W32.
7891
7892 W32 has a concept of "Namespaces" and "Namespace providers".
7893 These are used to present various name systems to applications in a
7894 generic way.
7895 Namespaces include DNS, mDNS, NLA and others. For each namespace any
7896 number of providers could be registered, and they are queried in an order
7897 of priority (which is adjustable).
7898
7899 Applications can resolve names by using WSALookupService*() family of
7900 functions.
7901
7902 However, these are WSA-only facilities. Common BSD socket functions for
7903 namespace resolutions are gethostbyname and getaddrinfo (among others).
7904 These functions are implemented internally (by default - by mswsock,
7905 which also implements the default DNS provider) as wrappers around
7906 WSALookupService*() functions (see "Sample Code for a Service Provider"
7907 on MSDN).
7908
7909 On W32 GNUnet builds a libw32nsp - a namespace provider, which can then be
7910 installed into the system by using w32nsp-install (and uninstalled by
7911 w32nsp-uninstall), as described in "Installation Handbook".
7912
7913 libw32nsp is very simple and has almost no dependencies. As a response to
7914 NSPLookupServiceBegin(), it only checks that the provider GUID passed to
7915 it by the caller matches GNUnet DNS Provider GUID,
7916 then connects to
7917 gnunet-gns-helper-service-w32 at 127.0.0.1:5353 (hardcoded) and sends the
7918 name resolution request there, returning the connected socket to the
7919 caller.
7920
7921 When the caller invokes NSPLookupServiceNext(), libw32nsp reads a
7922 completely formed reply from that socket, unmarshalls it, then gives
7923 it back to the caller.
7924
7925 At the moment gnunet-gns-helper-service-w32 is implemented to ever give
7926 only one reply, and subsequent calls to NSPLookupServiceNext() will fail
7927 with WSA_NODATA (first call to NSPLookupServiceNext() might also fail if
7928 GNS failed to find the name, or there was an error connecting to it).
7929
7930 gnunet-gns-helper-service-w32 does most of the processing:
7931
7932 @itemize @bullet
7933 @item Maintains a connection to GNS.
7934 @item Reads GNS config and loads appropriate keys.
7935 @item Checks service GUID and decides on the type of record to look up,
7936 refusing to make a lookup outright when unsupported service GUID is
7937 passed.
7938 @item Launches the lookup
7939 @end itemize
7940
7941 When lookup result arrives, gnunet-gns-helper-service-w32 forms a complete
7942 reply (including filling a WSAQUERYSETW structure and, possibly, a binary
7943 blob with a hostent structure for gethostbyname() client), marshalls it,
7944 and sends it back to libw32nsp. If no records were found, it sends an
7945 empty header.
7946
7947 This works for most normal applications that use gethostbyname() or
7948 getaddrinfo() to resolve names, but fails to do anything with
7949 applications that use alternative means of resolving names (such as
7950 sending queries to a DNS server directly by themselves).
7951 This includes some of well known utilities, like "ping" and "nslookup".
7952
7953 @node Importing DNS Zones into GNS
7954 @subsection Importing DNS Zones into GNS
7955
7956 This section discusses the challenges and problems faced when writing the
7957 Ascension tool. It also takes a look at possible improvements in the
7958 future.
7959
7960 @menu
7961 * Conversions between DNS and GNS::
7962 * DNS Zone Size::
7963 * Performance::
7964 @end menu
7965
7966 @cindex DNS Conversion
7967 @node Conversions between DNS and GNS
7968 @subsubsection Conversions between DNS and GNS
7969
7970 The differences between the two name systems lies in the details
7971 and is not always transparent.
7972 For instance an SRV record is converted to a GNS only BOX record.
7973
7974 This is done by converting to a BOX record from an existing SRV record:
7975
7976 @example
7977 # SRV
7978 # _service._proto.name. TTL class SRV priority weight port target
7979 _sip._tcp.example.com. 14000 IN SRV     0 0 5060 www.example.com.
7980 # BOX
7981 # TTL BOX flags port protocol recordtype priority weight port target
7982 14000 BOX n 5060 6 33 0 0 5060 www.example.com
7983 @end example
7984
7985 Other records that have such a transformation is the MX record type,
7986 as well as the SOA record type.
7987
7988 Transformation of a SOA record into GNS works as described in the
7989 following example. Very important to note are the rname and mname keys.
7990
7991 @example
7992 # BIND syntax for a clean SOA record
7993 @   IN SOA master.example.com. hostmaster.example.com. (
7994     2017030300 ; serial
7995     3600       ; refresh
7996     1800       ; retry
7997     604800     ; expire
7998     600 )      ; ttl
7999 # Recordline for adding the record
8000 $ gnunet-namestore -z example.com -a -n @ -t SOA -V rname=master.example.com \
8001   mname=hostmaster.example.com 2017030300,3600,1800,604800,600 -e 7200s
8002 @end example
8003
8004 The transformation of MX records is done in a simple way.
8005 @example
8006 # mail.example.com. 3600 IN MX 10 mail.example.com.
8007 $ gnunet-namestore -z example.com -n mail -R 3600 MX n 10,mail
8008 @end example
8009
8010 Finally, one of the biggest struggling points were the NS records that are found
8011 in top level domain zones. The intended behaviour for those is to add GNS2DNS
8012 records for those so that gnunet-gns can resolve records for those domains on
8013 its own. This requires migration of the DNS GLUE records as well, provided that
8014 they are within the same zone.
8015
8016 The following two examples show one record with a GLUE record and the other one
8017 does not have a GLUE record. This takes place in the 'com' TLD.
8018
8019 @example
8020 # ns1.example.com 86400 IN A 127.0.0.1
8021 # example.com 86400 IN NS ns1.example.com.
8022 $ gnunet-namestore -z com -n example -R 86400 GNS2DNS n example.com@@127.0.0.1
8023
8024 # example.com 86400 IN NS ns1.example.org.
8025 $ gnunet-namestore -z com -n example -R 86400 GNS2DNS n example.com@@ns1.example.org
8026 @end example
8027
8028 As you can see, one of the GNS2DNS records has an IP address listed and the
8029 other one a DNS name. For the first one there is a GLUE record to do the
8030 translation directly and the second one will issue another DNS query to figure
8031 out the IP of ns1.example.org.
8032
8033 A solution was found by creating a hierarchical zone structure in GNS and linking
8034 the zones using PKEY records to one another. This allows the resolution of the
8035 name servers to work within GNS while not taking control over unwanted zones.
8036
8037 Currently the following record types are supported:
8038 @itemize @bullet
8039 @item A
8040 @item AAAA
8041 @item CNAME
8042 @item MX
8043 @item NS
8044 @item SRV
8045 @item TXT
8046 @end itemize
8047
8048 This is not due to a technical limitation but rather a practical one. The
8049 problem occurs with DNSSEC enabled DNS zones. As records within those zones are
8050 signed periodically, and every new signature is an update to the zone, there are
8051 many revisions of zones. This results in a problem with bigger zones as there
8052 are lots of records that have been signed again but no major changes.  Also
8053 trying to add records that are unknown that require a different format take time
8054 as they cause a CLI call of the namestore.  Furthermore certain record types
8055 need transformation into a GNS compatible format which, depending on the record
8056 type, takes more time.
8057
8058 @node DNS Zone Size
8059 @subsubsection DNS Zone Size
8060
8061 Another very big problem exists with very large zones. When migrating a small
8062 zone the delay between adding of records and their expiry is negligible. However
8063 when working with a TLD zone that has more that 1 million records this delay
8064 becomes a problem.
8065
8066 Records will start to expire well before the zone has finished migrating. This
8067 causes unwanted anomalies when trying to resolve records.
8068
8069 A good solution has not been found yet. One of the idea that floated around was
8070 that the records should be added with the s (shadow) flag to keep the records
8071 resolvable even if they expired. However this would introduce the problem of how
8072 to detect if a record has been removed from the zone and would require deletion
8073 of said record(s).
8074
8075 Another problem that still persists is how to refresh records. Expired records
8076 are still displayed when calling gnunet-namestore but do not resolve with
8077 gnunet-gns. When doing incremental zone transfers this becomes especially
8078 apparent.
8079
8080 I estimate that the limit lies at about 200'000 records in a zone as this is
8081 the limit that my machine is capable of adding within one hour.  This was
8082 calculated by running cProfile on the application with a zone of 5000 records
8083 and calculating what abouts a much bigger zones with 8 million records would
8084 take. This results in a nice metric of records migrated per hour.
8085
8086 @node Performance
8087 @subsubsection Performance
8088 The performance when migrating a zone using the Ascension tool is limited by a
8089 handful of factors. First of all ascension is written in Python3 and calls the
8090 CLI tools of GNUnet. Furthermore all the records that are added to the same
8091 label are signed using the zones private key. This signing operation is very
8092 resource heavy and was optimized during development by adding the '-R'
8093 (Recordline) option to gnunet-namestore. This allows to add multiple records
8094 at once using the CLI.
8095
8096 The result of this was a much faster migration of TLD zones, as most records
8097 with the same label have two name servers.
8098
8099 Another improvement that could be made is with the addition of multiple threads
8100 when opening the GNUnet CLI tools. This could be implemented by simply creating
8101 more workers in the program but performance improvements were not tested.
8102
8103 During the entire development of Ascension sqlite was used as a database
8104 backend for GNUnet. Other backends have not been tested yet.
8105
8106 In conclusion there are many bottlenecks still around in the program, namely the
8107 signing process and the single threaded implementation. In the future a solution
8108 that uses the C API would be cleaner and better.
8109
8110 @cindex GNS Namecache
8111 @node GNS Namecache
8112 @section GNS Namecache
8113
8114
8115
8116 The NAMECACHE subsystem is responsible for caching (encrypted) resolution
8117 results of the GNU Name System (GNS). GNS makes zone information available
8118 to other users via the DHT. However, as accessing the DHT for every
8119 lookup is expensive (and as the DHT's local cache is lost whenever the
8120 peer is restarted), GNS uses the NAMECACHE as a more persistent cache for
8121 DHT lookups.
8122 Thus, instead of always looking up every name in the DHT, GNS first
8123 checks if the result is already available locally in the NAMECACHE.
8124 Only if there is no result in the NAMECACHE, GNS queries the DHT.
8125 The NAMECACHE stores data in the same (encrypted) format as the DHT.
8126 It thus makes no sense to iterate over all items in the
8127 NAMECACHE --- the NAMECACHE does not have a way to provide the keys
8128 required to decrypt the entries.
8129
8130 Blocks in the NAMECACHE share the same expiration mechanism as blocks in
8131 the DHT --- the block expires wheneever any of the records in
8132 the (encrypted) block expires.
8133 The expiration time of the block is the only information stored in
8134 plaintext. The NAMECACHE service internally performs all of the required
8135 work to expire blocks, clients do not have to worry about this.
8136 Also, given that NAMECACHE stores only GNS blocks that local users
8137 requested, there is no configuration option to limit the size of the
8138 NAMECACHE. It is assumed to be always small enough (a few MB) to fit on
8139 the drive.
8140
8141 The NAMECACHE supports the use of different database backends via a
8142 plugin API.
8143
8144 @menu
8145 * libgnunetnamecache::
8146 * The NAMECACHE Client-Service Protocol::
8147 * The NAMECACHE Plugin API::
8148 @end menu
8149
8150 @node libgnunetnamecache
8151 @subsection libgnunetnamecache
8152
8153
8154
8155 The NAMECACHE API consists of five simple functions. First, there is
8156 @code{GNUNET_NAMECACHE_connect} to connect to the NAMECACHE service.
8157 This returns the handle required for all other operations on the
8158 NAMECACHE. Using @code{GNUNET_NAMECACHE_block_cache} clients can insert a
8159 block into the cache.
8160 @code{GNUNET_NAMECACHE_lookup_block} can be used to lookup blocks that
8161 were stored in the NAMECACHE. Both operations can be canceled using
8162 @code{GNUNET_NAMECACHE_cancel}. Note that canceling a
8163 @code{GNUNET_NAMECACHE_block_cache} operation can result in the block
8164 being stored in the NAMECACHE --- or not. Cancellation primarily ensures
8165 that the continuation function with the result of the operation will no
8166 longer be invoked.
8167 Finally, @code{GNUNET_NAMECACHE_disconnect} closes the connection to the
8168 NAMECACHE.
8169
8170 The maximum size of a block that can be stored in the NAMECACHE is
8171 @code{GNUNET_NAMECACHE_MAX_VALUE_SIZE}, which is defined to be 63 kB.
8172
8173 @node The NAMECACHE Client-Service Protocol
8174 @subsection The NAMECACHE Client-Service Protocol
8175
8176
8177
8178 All messages in the NAMECACHE IPC protocol start with the
8179 @code{struct GNUNET_NAMECACHE_Header} which adds a request
8180 ID (32-bit integer) to the standard message header.
8181 The request ID is used to match requests with the
8182 respective responses from the NAMECACHE, as they are allowed to happen
8183 out-of-order.
8184
8185
8186 @menu
8187 * Lookup::
8188 * Store::
8189 @end menu
8190
8191 @node Lookup
8192 @subsubsection Lookup
8193
8194
8195
8196 The @code{struct LookupBlockMessage} is used to lookup a block stored in
8197 the cache.
8198 It contains the query hash. The NAMECACHE always responds with a
8199 @code{struct LookupBlockResponseMessage}. If the NAMECACHE has no
8200 response, it sets the expiration time in the response to zero.
8201 Otherwise, the response is expected to contain the expiration time, the
8202 ECDSA signature, the derived key and the (variable-size) encrypted data
8203 of the block.
8204
8205 @node Store
8206 @subsubsection Store
8207
8208
8209
8210 The @code{struct BlockCacheMessage} is used to cache a block in the
8211 NAMECACHE.
8212 It has the same structure as the @code{struct LookupBlockResponseMessage}.
8213 The service responds with a @code{struct BlockCacheResponseMessage} which
8214 contains the result of the operation (success or failure).
8215 In the future, we might want to make it possible to provide an error
8216 message as well.
8217
8218 @node The NAMECACHE Plugin API
8219 @subsection The NAMECACHE Plugin API
8220
8221
8222 The NAMECACHE plugin API consists of two functions, @code{cache_block} to
8223 store a block in the database, and @code{lookup_block} to lookup a block
8224 in the database.
8225
8226
8227 @menu
8228 * Lookup2::
8229 * Store2::
8230 @end menu
8231
8232 @node Lookup2
8233 @subsubsection Lookup2
8234
8235
8236
8237 The @code{lookup_block} function is expected to return at most one block
8238 to the iterator, and return @code{GNUNET_NO} if there were no non-expired
8239 results.
8240 If there are multiple non-expired results in the cache, the lookup is
8241 supposed to return the result with the largest expiration time.
8242
8243 @node Store2
8244 @subsubsection Store2
8245
8246
8247
8248 The @code{cache_block} function is expected to try to store the block in
8249 the database, and return @code{GNUNET_SYSERR} if this was not possible
8250 for any reason.
8251 Furthermore, @code{cache_block} is expected to implicitly perform cache
8252 maintenance and purge blocks from the cache that have expired. Note that
8253 @code{cache_block} might encounter the case where the database already has
8254 another block stored under the same key. In this case, the plugin must
8255 ensure that the block with the larger expiration time is preserved.
8256 Obviously, this can done either by simply adding new blocks and selecting
8257 for the most recent expiration time during lookup, or by checking which
8258 block is more recent during the store operation.
8259
8260 @cindex REVOCATION Subsystem
8261 @node REVOCATION Subsystem
8262 @section REVOCATION Subsystem
8263
8264
8265 The REVOCATION subsystem is responsible for key revocation of Egos.
8266 If a user learns that theis private key has been compromised or has lost
8267 it, they can use the REVOCATION system to inform all of the other users
8268 that their private key is no longer valid.
8269 The subsystem thus includes ways to query for the validity of keys and to
8270 propagate revocation messages.
8271
8272 @menu
8273 * Dissemination::
8274 * Revocation Message Design Requirements::
8275 * libgnunetrevocation::
8276 * The REVOCATION Client-Service Protocol::
8277 * The REVOCATION Peer-to-Peer Protocol::
8278 @end menu
8279
8280 @node Dissemination
8281 @subsection Dissemination
8282
8283
8284
8285 When a revocation is performed, the revocation is first of all
8286 disseminated by flooding the overlay network.
8287 The goal is to reach every peer, so that when a peer needs to check if a
8288 key has been revoked, this will be purely a local operation where the
8289 peer looks at its local revocation list. Flooding the network is also the
8290 most robust form of key revocation --- an adversary would have to control
8291 a separator of the overlay graph to restrict the propagation of the
8292 revocation message. Flooding is also very easy to implement --- peers that
8293 receive a revocation message for a key that they have never seen before
8294 simply pass the message to all of their neighbours.
8295
8296 Flooding can only distribute the revocation message to peers that are
8297 online.
8298 In order to notify peers that join the network later, the revocation
8299 service performs efficient set reconciliation over the sets of known
8300 revocation messages whenever two peers (that both support REVOCATION
8301 dissemination) connect.
8302 The SET service is used to perform this operation efficiently.
8303
8304 @node Revocation Message Design Requirements
8305 @subsection Revocation Message Design Requirements
8306
8307
8308
8309 However, flooding is also quite costly, creating O(|E|) messages on a
8310 network with |E| edges.
8311 Thus, revocation messages are required to contain a proof-of-work, the
8312 result of an expensive computation (which, however, is cheap to verify).
8313 Only peers that have expended the CPU time necessary to provide
8314 this proof will be able to flood the network with the revocation message.
8315 This ensures that an attacker cannot simply flood the network with
8316 millions of revocation messages. The proof-of-work required by GNUnet is
8317 set to take days on a typical PC to compute; if the ability to quickly
8318 revoke a key is needed, users have the option to pre-compute revocation
8319 messages to store off-line and use instantly after their key has expired.
8320
8321 Revocation messages must also be signed by the private key that is being
8322 revoked. Thus, they can only be created while the private key is in the
8323 possession of the respective user. This is another reason to create a
8324 revocation message ahead of time and store it in a secure location.
8325
8326 @node libgnunetrevocation
8327 @subsection libgnunetrevocation
8328
8329
8330
8331 The REVOCATION API consists of two parts, to query and to issue
8332 revocations.
8333
8334
8335 @menu
8336 * Querying for revoked keys::
8337 * Preparing revocations::
8338 * Issuing revocations::
8339 @end menu
8340
8341 @node Querying for revoked keys
8342 @subsubsection Querying for revoked keys
8343
8344
8345
8346 @code{GNUNET_REVOCATION_query} is used to check if a given ECDSA public
8347 key has been revoked.
8348 The given callback will be invoked with the result of the check.
8349 The query can be canceled using @code{GNUNET_REVOCATION_query_cancel} on
8350 the return value.
8351
8352 @node Preparing revocations
8353 @subsubsection Preparing revocations
8354
8355
8356
8357 It is often desirable to create a revocation record ahead-of-time and
8358 store it in an off-line location to be used later in an emergency.
8359 This is particularly true for GNUnet revocations, where performing the
8360 revocation operation itself is computationally expensive and thus is
8361 likely to take some time.
8362 Thus, if users want the ability to perform revocations quickly in an
8363 emergency, they must pre-compute the revocation message.
8364 The revocation API enables this with two functions that are used to
8365 compute the revocation message, but not trigger the actual revocation
8366 operation.
8367
8368 @code{GNUNET_REVOCATION_check_pow} should be used to calculate the
8369 proof-of-work required in the revocation message. This function takes the
8370 public key, the required number of bits for the proof of work (which in
8371 GNUnet is a network-wide constant) and finally a proof-of-work number as
8372 arguments.
8373 The function then checks if the given proof-of-work number is a valid
8374 proof of work for the given public key. Clients preparing a revocation
8375 are expected to call this function repeatedly (typically with a
8376 monotonically increasing sequence of numbers of the proof-of-work number)
8377 until a given number satisfies the check.
8378 That number should then be saved for later use in the revocation
8379 operation.
8380
8381 @code{GNUNET_REVOCATION_sign_revocation} is used to generate the
8382 signature that is required in a revocation message.
8383 It takes the private key that (possibly in the future) is to be revoked
8384 and returns the signature.
8385 The signature can again be saved to disk for later use, which will then
8386 allow performing a revocation even without access to the private key.
8387
8388 @node Issuing revocations
8389 @subsubsection Issuing revocations
8390
8391
8392 Given a ECDSA public key, the signature from @code{GNUNET_REVOCATION_sign}
8393 and the proof-of-work,
8394 @code{GNUNET_REVOCATION_revoke} can be used to perform the
8395 actual revocation. The given callback is called upon completion of the
8396 operation. @code{GNUNET_REVOCATION_revoke_cancel} can be used to stop the
8397 library from calling the continuation; however, in that case it is
8398 undefined whether or not the revocation operation will be executed.
8399
8400 @node The REVOCATION Client-Service Protocol
8401 @subsection The REVOCATION Client-Service Protocol
8402
8403
8404 The REVOCATION protocol consists of four simple messages.
8405
8406 A @code{QueryMessage} containing a public ECDSA key is used to check if a
8407 particular key has been revoked. The service responds with a
8408 @code{QueryResponseMessage} which simply contains a bit that says if the
8409 given public key is still valid, or if it has been revoked.
8410
8411 The second possible interaction is for a client to revoke a key by
8412 passing a @code{RevokeMessage} to the service. The @code{RevokeMessage}
8413 contains the ECDSA public key to be revoked, a signature by the
8414 corresponding private key and the proof-of-work, The service responds
8415 with a @code{RevocationResponseMessage} which can be used to indicate
8416 that the @code{RevokeMessage} was invalid (i.e. proof of work incorrect),
8417 or otherwise indicates that the revocation has been processed
8418 successfully.
8419
8420 @node The REVOCATION Peer-to-Peer Protocol
8421 @subsection The REVOCATION Peer-to-Peer Protocol
8422
8423
8424
8425 Revocation uses two disjoint ways to spread revocation information among
8426 peers.
8427 First of all, P2P gossip exchanged via CORE-level neighbours is used to
8428 quickly spread revocations to all connected peers.
8429 Second, whenever two peers (that both support revocations) connect,
8430 the SET service is used to compute the union of the respective revocation
8431 sets.
8432
8433 In both cases, the exchanged messages are @code{RevokeMessage}s which
8434 contain the public key that is being revoked, a matching ECDSA signature,
8435 and a proof-of-work.
8436 Whenever a peer learns about a new revocation this way, it first
8437 validates the signature and the proof-of-work, then stores it to disk
8438 (typically to a file $GNUNET_DATA_HOME/revocation.dat) and finally
8439 spreads the information to all directly connected neighbours.
8440
8441 For computing the union using the SET service, the peer with the smaller
8442 hashed peer identity will connect (as a "client" in the two-party set
8443 protocol) to the other peer after one second (to reduce traffic spikes
8444 on connect) and initiate the computation of the set union.
8445 All revocation services use a common hash to identify the SET operation
8446 over revocation sets.
8447
8448 The current implementation accepts revocation set union operations from
8449 all peers at any time; however, well-behaved peers should only initiate
8450 this operation once after establishing a connection to a peer with a
8451 larger hashed peer identity.
8452
8453 @cindex FS
8454 @cindex FS Subsystem
8455 @node File-sharing (FS) Subsystem
8456 @section File-sharing (FS) Subsystem
8457
8458
8459
8460 This chapter describes the details of how the file-sharing service works.
8461 As with all services, it is split into an API (libgnunetfs), the service
8462 process (gnunet-service-fs) and user interface(s).
8463 The file-sharing service uses the datastore service to store blocks and
8464 the DHT (and indirectly datacache) for lookups for non-anonymous
8465 file-sharing.
8466 Furthermore, the file-sharing service uses the block library (and the
8467 block fs plugin) for validation of DHT operations.
8468
8469 In contrast to many other services, libgnunetfs is rather complex since
8470 the client library includes a large number of high-level abstractions;
8471 this is necessary since the Fs service itself largely only operates on
8472 the block level.
8473 The FS library is responsible for providing a file-based abstraction to
8474 applications, including directories, meta data, keyword search,
8475 verification, and so on.
8476
8477 The method used by GNUnet to break large files into blocks and to use
8478 keyword search is called the
8479 "Encoding for Censorship Resistant Sharing" (ECRS).
8480 ECRS is largely implemented in the fs library; block validation is also
8481 reflected in the block FS plugin and the FS service.
8482 ECRS on-demand encoding is implemented in the FS service.
8483
8484 NOTE: The documentation in this chapter is quite incomplete.
8485
8486 @menu
8487 * Encoding for Censorship-Resistant Sharing (ECRS)::
8488 * File-sharing persistence directory structure::
8489 @end menu
8490
8491 @cindex ECRS
8492 @cindex Encoding for Censorship-Resistant Sharing
8493 @node Encoding for Censorship-Resistant Sharing (ECRS)
8494 @subsection Encoding for Censorship-Resistant Sharing (ECRS)
8495
8496
8497
8498 When GNUnet shares files, it uses a content encoding that is called ECRS,
8499 the Encoding for Censorship-Resistant Sharing.
8500 Most of ECRS is described in the (so far unpublished) research paper
8501 attached to this page. ECRS obsoletes the previous ESED and ESED II
8502 encodings which were used in GNUnet before version 0.7.0.
8503 The rest of this page assumes that the reader is familiar with the
8504 attached paper. What follows is a description of some minor extensions
8505 that GNUnet makes over what is described in the paper.
8506 The reason why these extensions are not in the paper is that we felt
8507 that they were obvious or trivial extensions to the original scheme and
8508 thus did not warrant space in the research report.
8509
8510 @menu
8511 * Namespace Advertisements::
8512 * KSBlocks::
8513 @end menu
8514
8515 @node Namespace Advertisements
8516 @subsubsection Namespace Advertisements
8517
8518
8519 @c %**FIXME: all zeroses -> ?
8520
8521 An @code{SBlock} with identifier all zeros is a signed
8522 advertisement for a namespace. This special @code{SBlock} contains
8523 metadata describing the content of the namespace.
8524 Instead of the name of the identifier for a potential update, it contains
8525 the identifier for the root of the namespace.
8526 The URI should always be empty. The @code{SBlock} is signed with the
8527 content provider's RSA private key (just like any other SBlock). Peers
8528 can search for @code{SBlock}s in order to find out more about a namespace.
8529
8530 @node KSBlocks
8531 @subsubsection KSBlocks
8532
8533
8534
8535 GNUnet implements @code{KSBlocks} which are @code{KBlocks} that, instead
8536 of encrypting a CHK and metadata, encrypt an @code{SBlock} instead.
8537 In other words, @code{KSBlocks} enable GNUnet to find @code{SBlocks}
8538 using the global keyword search.
8539 Usually the encrypted @code{SBlock} is a namespace advertisement.
8540 The rationale behind @code{KSBlock}s and @code{SBlock}s is to enable
8541 peers to discover namespaces via keyword searches, and, to associate
8542 useful information with namespaces. When GNUnet finds @code{KSBlocks}
8543 during a normal keyword search, it adds the information to an internal
8544 list of discovered namespaces. Users looking for interesting namespaces
8545 can then inspect this list, reducing the need for out-of-band discovery
8546 of namespaces.
8547 Naturally, namespaces (or more specifically, namespace advertisements) can
8548 also be referenced from directories, but @code{KSBlock}s should make it
8549 easier to advertise namespaces for the owner of the pseudonym since they
8550 eliminate the need to first create a directory.
8551
8552 Collections are also advertised using @code{KSBlock}s.
8553
8554 @c https://old.gnunet.org/sites/default/files/ecrs.pdf
8555
8556 @node File-sharing persistence directory structure
8557 @subsection File-sharing persistence directory structure
8558
8559
8560
8561 This section documents how the file-sharing library implements
8562 persistence of file-sharing operations and specifically the resulting
8563 directory structure.
8564 This code is only active if the @code{GNUNET_FS_FLAGS_PERSISTENCE} flag
8565 was set when calling @code{GNUNET_FS_start}.
8566 In this case, the file-sharing library will try hard to ensure that all
8567 major operations (searching, downloading, publishing, unindexing) are
8568 persistent, that is, can live longer than the process itself.
8569 More specifically, an operation is supposed to live until it is
8570 explicitly stopped.
8571
8572 If @code{GNUNET_FS_stop} is called before an operation has been stopped, a
8573 @code{SUSPEND} event is generated and then when the process calls
8574 @code{GNUNET_FS_start} next time, a @code{RESUME} event is generated.
8575 Additionally, even if an application crashes (segfault, SIGKILL, system
8576 crash) and hence @code{GNUNET_FS_stop} is never called and no
8577 @code{SUSPEND} events are generated, operations are still resumed (with
8578 @code{RESUME} events).
8579 This is implemented by constantly writing the current state of the
8580 file-sharing operations to disk.
8581 Specifically, the current state is always written to disk whenever
8582 anything significant changes (the exception are block-wise progress in
8583 publishing and unindexing, since those operations would be slowed down
8584 significantly and can be resumed cheaply even without detailed
8585 accounting).
8586 Note that if the process crashes (or is killed) during a serialization
8587 operation, FS does not guarantee that this specific operation is
8588 recoverable (no strict transactional semantics, again for performance
8589 reasons). However, all other unrelated operations should resume nicely.
8590
8591 Since we need to serialize the state continuously and want to recover as
8592 much as possible even after crashing during a serialization operation,
8593 we do not use one large file for serialization.
8594 Instead, several directories are used for the various operations.
8595 When @code{GNUNET_FS_start} executes, the master directories are scanned
8596 for files describing operations to resume.
8597 Sometimes, these operations can refer to related operations in child
8598 directories which may also be resumed at this point.
8599 Note that corrupted files are cleaned up automatically.
8600 However, dangling files in child directories (those that are not
8601 referenced by files from the master directories) are not automatically
8602 removed.
8603
8604 Persistence data is kept in a directory that begins with the "STATE_DIR"
8605 prefix from the configuration file
8606 (by default, "$SERVICEHOME/persistence/") followed by the name of the
8607 client as given to @code{GNUNET_FS_start} (for example, "gnunet-gtk")
8608 followed by the actual name of the master or child directory.
8609
8610 The names for the master directories follow the names of the operations:
8611
8612 @itemize @bullet
8613 @item "search"
8614 @item "download"
8615 @item "publish"
8616 @item "unindex"
8617 @end itemize
8618
8619 Each of the master directories contains names (chosen at random) for each
8620 active top-level (master) operation.
8621 Note that a download that is associated with a search result is not a
8622 top-level operation.
8623
8624 In contrast to the master directories, the child directories are only
8625 consulted when another operation refers to them.
8626 For each search, a subdirectory (named after the master search
8627 synchronization file) contains the search results.
8628 Search results can have an associated download, which is then stored in
8629 the general "download-child" directory.
8630 Downloads can be recursive, in which case children are stored in
8631 subdirectories mirroring the structure of the recursive download
8632 (either starting in the master "download" directory or in the
8633 "download-child" directory depending on how the download was initiated).
8634 For publishing operations, the "publish-file" directory contains
8635 information about the individual files and directories that are part of
8636 the publication.
8637 However, this directory structure is flat and does not mirror the
8638 structure of the publishing operation.
8639 Note that unindex operations cannot have associated child operations.
8640
8641 @cindex REGEX subsystem
8642 @node REGEX Subsystem
8643 @section REGEX Subsystem
8644
8645
8646
8647 Using the REGEX subsystem, you can discover peers that offer a particular
8648 service using regular expressions.
8649 The peers that offer a service specify it using a regular expressions.
8650 Peers that want to patronize a service search using a string.
8651 The REGEX subsystem will then use the DHT to return a set of matching
8652 offerers to the patrons.
8653
8654 For the technical details, we have Max's defense talk and Max's Master's
8655 thesis.
8656
8657 @c An additional publication is under preparation and available to
8658 @c team members (in Git).
8659 @c FIXME: Where is the file? Point to it. Assuming that it's szengel2012ms
8660
8661 @menu
8662 * How to run the regex profiler::
8663 @end menu
8664
8665 @node How to run the regex profiler
8666 @subsection How to run the regex profiler
8667
8668
8669
8670 The gnunet-regex-profiler can be used to profile the usage of mesh/regex
8671 for a given set of regular expressions and strings.
8672 Mesh/regex allows you to announce your peer ID under a certain regex and
8673 search for peers matching a particular regex using a string.
8674 See @uref{https://old.gnunet.org/szengel2012ms, szengel2012ms} for a full
8675 introduction.
8676
8677 First of all, the regex profiler uses GNUnet testbed, thus all the
8678 implications for testbed also apply to the regex profiler
8679 (for example you need password-less ssh login to the machines listed in
8680 your hosts file).
8681
8682 @strong{Configuration}
8683
8684 Moreover, an appropriate configuration file is needed.
8685 Generally you can refer to the
8686 @file{contrib/regex_profiler_infiniband.conf} file in the sourcecode
8687 of GNUnet for an example configuration.
8688 In the following paragraph the important details are highlighted.
8689
8690 Announcing of the regular expressions is done by the
8691 gnunet-daemon-regexprofiler, therefore you have to make sure it is
8692 started, by adding it to the START_ON_DEMAND set of ARM:
8693
8694 @example
8695 [regexprofiler]
8696 START_ON_DEMAND = YES
8697 @end example
8698
8699 @noindent
8700 Furthermore you have to specify the location of the binary:
8701
8702 @example
8703 [regexprofiler]
8704 # Location of the gnunet-daemon-regexprofiler binary.
8705 BINARY = /home/szengel/gnunet/src/mesh/.libs/gnunet-daemon-regexprofiler
8706 # Regex prefix that will be applied to all regular expressions and
8707 # search string.
8708 REGEX_PREFIX = "GNVPN-0001-PAD"
8709 @end example
8710
8711 @noindent
8712 When running the profiler with a large scale deployment, you probably
8713 want to reduce the workload of each peer.
8714 Use the following options to do this.
8715
8716 @example
8717 [dht]
8718 # Force network size estimation
8719 FORCE_NSE = 1
8720
8721 [dhtcache]
8722 DATABASE = heap
8723 # Disable RC-file for Bloom filter? (for benchmarking with limited IO
8724 # availability)
8725 DISABLE_BF_RC = YES
8726 # Disable Bloom filter entirely
8727 DISABLE_BF = YES
8728
8729 [nse]
8730 # Minimize proof-of-work CPU consumption by NSE
8731 WORKBITS = 1
8732 @end example
8733
8734 @noindent
8735 @strong{Options}
8736
8737 To finally run the profiler some options and the input data need to be
8738 specified on the command line.
8739
8740 @example
8741 gnunet-regex-profiler -c config-file -d log-file -n num-links \
8742 -p path-compression-length -s search-delay -t matching-timeout \
8743 -a num-search-strings hosts-file policy-dir search-strings-file
8744 @end example
8745
8746 @noindent
8747 Where...
8748
8749 @itemize @bullet
8750 @item ... @code{config-file} means the configuration file created earlier.
8751 @item ... @code{log-file} is the file where to write statistics output.
8752 @item ... @code{num-links} indicates the number of random links between
8753 started peers.
8754 @item ... @code{path-compression-length} is the maximum path compression
8755 length in the DFA.
8756 @item ... @code{search-delay} time to wait between peers finished linking
8757 and starting to match strings.
8758 @item ... @code{matching-timeout} timeout after which to cancel the
8759 searching.
8760 @item ... @code{num-search-strings} number of strings in the
8761 search-strings-file.
8762 @item ... the @code{hosts-file} should contain a list of hosts for the
8763 testbed, one per line in the following format:
8764
8765 @itemize @bullet
8766 @item @code{user@@host_ip:port}
8767 @end itemize
8768 @item ... the @code{policy-dir} is a folder containing text files
8769 containing one or more regular expressions. A peer is started for each
8770 file in that folder and the regular expressions in the corresponding file
8771 are announced by this peer.
8772 @item ... the @code{search-strings-file} is a text file containing search
8773 strings, one in each line.
8774 @end itemize
8775
8776 @noindent
8777 You can create regular expressions and search strings for every AS in the
8778 Internet using the attached scripts. You need one of the
8779 @uref{http://data.caida.org/datasets/routing/routeviews-prefix2as/, CAIDA routeviews prefix2as}
8780 data files for this. Run
8781
8782 @example
8783 create_regex.py <filename> <output path>
8784 @end example
8785
8786 @noindent
8787 to create the regular expressions and
8788
8789 @example
8790 create_strings.py <input path> <outfile>
8791 @end example
8792
8793 @noindent
8794 to create a search strings file from the previously created
8795 regular expressions.
8796
8797 @cindex REST subsystem
8798 @node REST Subsystem
8799 @section REST Subsystem
8800
8801
8802
8803 Using the REST subsystem, you can expose REST-based APIs or services.
8804 The REST service is designed as a pluggable architecture.
8805 To create a new REST endpoint, simply add a library in the form
8806 ``plugin_rest_*''.
8807 The REST service will automatically load all REST plugins on startup.
8808
8809 @strong{Configuration}
8810
8811 The REST service can be configured in various ways.
8812 The reference config file can be found in
8813 @file{src/rest/rest.conf}:
8814 @example
8815 [rest]
8816 REST_PORT=7776
8817 REST_ALLOW_HEADERS=Authorization,Accept,Content-Type
8818 REST_ALLOW_ORIGIN=*
8819 REST_ALLOW_CREDENTIALS=true
8820 @end example
8821
8822 The port as well as
8823 @deffn{cross-origin resource sharing} (CORS)
8824 @end deffn
8825 headers that are supposed to be advertised by the rest service are
8826 configurable.
8827
8828 @menu
8829 * Namespace considerations::
8830 * Endpoint documentation::
8831 @end menu
8832
8833 @node Namespace considerations
8834 @subsection Namespace considerations
8835
8836 The @command{gnunet-rest-service} will load all plugins that are installed.
8837 As such it is important that the endpoint namespaces do not clash.
8838
8839 For example, plugin X might expose the endpoint ``/xxx'' while plugin Y
8840 exposes endpoint ``/xxx/yyy''.
8841 This is a problem if plugin X is also supposed to handle a call
8842 to ``/xxx/yyy''.
8843 Currently the REST service will not complain or warn about such clashes,
8844 so please make sure that endpoints are unambiguous.
8845
8846 @node Endpoint documentation
8847 @subsection Endpoint documentation
8848
8849 This is WIP. Endpoints should be documented appropriately.
8850 Preferably using annotations.